pointers - C, what does this line do? -
i saw line of code topic @ codegolf.
struct { int (*log)(const char *,...); } console = { printf }; this original post https://codegolf.stackexchange.com/questions/24623/write-program-in-your-favorite-language-in-another-language although know c/c++, cannot understand line. thought create synonyms, use typefs , (console={printf}). also, dont understand struct @ all. why struct , going on inside... casting of pointers? ,.... see inside?
so, let's work outside in:
struct { t m; } console = { }; you're defining anonymous struct type single member m of type t, using type declare variable named console , initializing initializer { }.
so t, m, , i?
the member declaration
int (*log)(const char *, ...); breaks down as
log -- log (*log) -- pointer (*log)( ) -- function (*log)(const char *, ...) -- taking fixed parameter of type const char *, followed variable number of parameters int (*log)(const char *, ...); -- returning int so, member m named log, , type t int (*)(const char *, ...).
the initializer expression is
{ printf } the prototype printf
int printf(const char *, ...); except when operand of sizeof or unary & operators, function designator of type "function returning t" converted expression of type "pointer function returning t". thus, type of expression printf within initializer is
int (*)(const char *, ...); look familiar? that's same type of log member.
tl;dr version
you're creating struct type containing single member named log, used point function printf. used this:
struct { int (*log)(const char *, ...); } console = { printf }; ... console.log("%s\n", "this test");
Comments
Post a Comment