5 ms·
What has referring to a variable twice got to do with whether it should be a macro or function?
by foo101 7y ago
What has referring to a variable twice got to do with whether it should be a macro or function?
- mras0 7y agoBecause it's a standard pitfall: https://gcc.gnu.org/onlinedocs/cpp/Duplication-of-Side-Effects.html#Duplication-of-Side-Effects https://gcc.gnu.org/onlinedocs/cpp/Duplication-of-Side-Effec...
- jfk13 7y agoIf the strcp() macro is used with a function as the first argument (or an expression that has side-effects), it's not obvious at the call site (or, probably, intended by the programmer) that the argument will be evaluated twice. E.g. suppose we write something like char* buf = strcp(((char*)malloc(4)), "foobar", 4); expecting this to copy the beginning of the string "foobar" into a newly-allocated 4-byte buffer. Oops... this will actually call malloc twice (leaking the first buffer), and it won't have written the intended '\0' into the buffer that actually ends up getting used, so all bets are off... If strcp were a function, its first argument would be evaluated just once, and it would work as intended.