Languages/C/CompilerTrust

From UIT
Revision as of 11:25, 7 January 2014 by Pim (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Contents

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.
Personal tools
Namespaces
Variants
Actions
Navigation
Browse
Toolbox