From 2a0f3afe20d5b6eaae9eed4d01393a70fa2abc39 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Sat, 1 May 2021 19:12:40 +0100 Subject: fix < and > in pre --- content/html/gemfeed/2016-11-20-methods-in-c.html | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'content/html/gemfeed/2016-11-20-methods-in-c.html') diff --git a/content/html/gemfeed/2016-11-20-methods-in-c.html b/content/html/gemfeed/2016-11-20-methods-in-c.html index 2bf02ed1..3b2efa46 100644 --- a/content/html/gemfeed/2016-11-20-methods-in-c.html +++ b/content/html/gemfeed/2016-11-20-methods-in-c.html @@ -25,7 +25,7 @@ li { color: #98be65; }

Example

Lets have a look at the following sample program. Basically all you have to do is to add a function pointer such as "calculate" to the definition of struct "something_s". Later, during the struct initialization, assign a function address to that function pointer:

-#include 
+#include gt;
 
 typedef struct {
     double (*calculate)(const double, const double);
@@ -53,26 +53,26 @@ int main(void) {
 
     const double a = 3, b = 2;
 
-    printf("%s(%f, %f) => %f\n", mult.name, a, b, mult.calculate(a,b));
-    printf("%s(%f, %f) => %f\n", div.name, a, b, div.calculate(a,b));
+    printf("%s(%f, %f) =>gt; %f\n", mult.name, a, b, mult.calculate(a,b));
+    printf("%s(%f, %f) =>gt; %f\n", div.name, a, b, div.calculate(a,b));
 }
 

As you can see you can call the function (pointed by the function pointer) the same way as in C++ or Java via:

-printf("%s(%f, %f) => %f\n", mult.name, a, b, mult.calculate(a,b));
-printf("%s(%f, %f) => %f\n", div.name, a, b, div.calculate(a,b));
+printf("%s(%f, %f) =>gt; %f\n", mult.name, a, b, mult.calculate(a,b));
+printf("%s(%f, %f) =>gt; %f\n", div.name, a, b, div.calculate(a,b));
 

However, that's just syntactic sugar for:

-printf("%s(%f, %f) => %f\n", mult.name, a, b, (*mult.calculate)(a,b));
-printf("%s(%f, %f) => %f\n", div.name, a, b, (*div.calculate)(a,b));
+printf("%s(%f, %f) =>gt; %f\n", mult.name, a, b, (*mult.calculate)(a,b));
+printf("%s(%f, %f) =>gt; %f\n", div.name, a, b, (*div.calculate)(a,b));
 

Output:

 pbuetow ~/git/blog/source [38268]% gcc methods-in-c.c -o methods-in-c
 pbuetow ~/git/blog/source [38269]% ./methods-in-c
-Multiplication(3.000000, 2.000000) => 6.000000
-Division(3.000000, 2.000000) => 1.500000
+Multiplication(3.000000, 2.000000) =>gt; 6.000000
+Division(3.000000, 2.000000) =>gt; 1.500000
 

Not complicated at all, but nice to know and helps to make the code easier to read!

Taking it further

-- cgit v1.2.3