c - Why does this define macro perform a cast? -


i have function-like macro takes in enum return code , function call.

#define handle_call(result,call) \     { \         result callresult = call; \         result* resultvar = (result*)result; \         // additional processing         (*resultvar) = callresult; \     } while(0) 

does fancy pointer casting result* , subsequent de-referencing gain anything? is, there advantage doing on just:

callresult = call; // additional processing *result = callresult; 

the macro used this:

result result; handle_call(&result,some_function()); 

by way, isn't code , i'm not power c user i'm trying understand if there logic behind doing this.

i think gives you, user of macro can pass in pointer of old type, not result*. i'd either way, or if wanted allow (for example) void* macro argument i'd write *(result*)(result) = callresult;.

there's thing might be, depending rest of macro looks like. "some additional processing" mention resultvar @ all, or line (*resultvar) = callresult; conditional? if so, resultvar exists in order ensure macro evaluates each of arguments exactly once, , therefore behaves more function call if evaluated them other number of times (including zero).

so, if call in loop handle_call(output++, *input++) vaguely predictable. @ least, provided output result* macro author intended. i'm still not sure cast gives you, other allowing different argument types void* or char*.

there situations make difference whether have cast or not. example, consider:

typedef double result;  int foo() { return 1; } int i; handle_call(&i, foo()); 

if typedef double result; isn't visible on screen, other 3 lines appear pretty innocuous. what's wrong assigning int int, right? once macro expanded, bad stuff happens when cast int* double*. cast, bad stuff undefined behavior, double bigger int , overruns memory i. if you're lucky, you'll compiler warning "strict aliasing".

without cast can't double* resultvar = &i;, original macro change catches error , rejects code, instead of doing nasty. version *result = callresult; works, provided double can accurately represent every value of int. ieee double , int smaller 53 bits, can.

presumably result struct, , nobody write code give above. think serves example why macros end being more fiddly think.


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -