Created
January 18, 2017 01:29
-
-
Save Bueddl/913f92e274022f277814788a9c644545 to your computer and use it in GitHub Desktop.
An array of functions that return functions that return void :>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* (C) 2017 Sebastian Büttner <sebastian.buettner@iem.thm.de> */ | |
#include <stdio.h> | |
/* This is about functions returning functions that return void and take no arguments (see below). */ | |
void func() | |
{ | |
printf("func()\n"); | |
} | |
/* Approach A | |
* | |
* Messing things up... | |
*/ | |
/* A function that returns a function that retuns void... */ | |
void (*(func_a)())() | |
{ | |
return &func; | |
} | |
void test_a() | |
{ | |
/* An array (of unspecified length) of functions returning functions that return void */ | |
void (*(*f[])())() = { | |
&func_a, | |
&func_b | |
}; | |
int i; | |
for (i = 0; i < 2; i++) | |
f[i]()(); | |
} | |
/* Approach B | |
* | |
* Using typedefs to keep simple return and variable types and the code readable. | |
*/ | |
/* A function ptr that returns void */ | |
typedef void (*fn_void_t)(); | |
/* A function ptr type that returns fn_void_t (see above) */ | |
typedef fn_void_t (*fn_fnvoid_t)(); | |
/* A function that returns fn_void_t (see above) */ | |
fn_void_t func_b() | |
{ | |
return &func; | |
} | |
void test_b() | |
{ | |
/* An array of fn_fnvoid_t (see above) */ | |
fn_fnvoid_t g[] = { | |
&func_a, | |
&func_b | |
}; | |
int i; | |
for (i = 0; i < 2; i++) | |
g[i]()(); | |
} | |
/* Test */ | |
int main() | |
{ | |
test_a(); | |
test_b(); | |
/* TL;DR: You can be an asshole of a programmer, but you should not be... :) */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment