Languages/C/CompilerTrust
From UIT
|
Trust your compiler
macros VS functions
Macros can be hard to write, are not easily readable and prone to type errors. Macros can have side effects when using arguments multiple time. Functions can be slower than macros, but a good compiler will automatically inline simple static functions.
So, as always, prefer maintainability over (apparent) speedup.
Here are 2 way to square a numbers:
#define SQUARE(n) (n*n) static uint32_t square(uint32_t n) { return n*n; }
- Exercise for the reader #1 : what if you call SQUARE(i++) ?
- Exercise for the reader #2 : rewrite the square macro so it works with SQUARE(i++).
- Exercise for the reader #3 : rewrite the square macro so it works with SQUARE(i++) in a portable way.