3 ms·
You can even do #define free(p) do { free(p); p = NULL; } while(0) And when you want to call the original free: (free)(p); The preprocessor will not sub
by okl 6y ago
You can even do
#define free(p) do { free(p); p = NULL; } while(0)
And when you want to call the original free:
(free)(p);
The preprocessor will not substitute this occurence of free.
- devenblake 6y agoC n00b here - why the `do {} while(0)`? Couldn't you just do something like `#define free(p) { free(p); p = NULL; }`?
- deaddodo 6y agoSemi-experienced C user here, I believe the anonymous block is perfectly adequate here. No idea why they are wrapping it in a single instance do loop, unless they’re unaware of block scoping or I’m unaware of some UB here.
- btrask 6y agodo {} while(0) is a common idiom for macros in C, because it consumes the trailing semicolon, which a bare {} block doesn't do. if(x) MACRO(); else something(); expands to if(x) { ... }; // Error! else something();