Languages/C/CompilerTrust

From UIT
(Difference between revisions)
Jump to: navigation, search
(Created page with "{{public}} {{TOC right}} == Trust your compiler == === macros VS functions === Macros can be hard to write, are not easily readable and prone to type errors. Macros can have ...")
 
 
Line 4: Line 4:
 
== Trust your compiler ==
 
== Trust your compiler ==
 
=== macros VS functions ===
 
=== macros VS functions ===
Macros can be hard to write, are not easily readable and prone to type errors.
+
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.
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.
 
Functions can be slower than macros, but a good compiler will automatically inline simple static functions.
  
 
So, as always, prefer maintainability over (apparent) speedup.
 
So, as always, prefer maintainability over (apparent) speedup.
  
 +
Here are 2 way to square a numbers:
 
<source lang='c'>
 
<source lang='c'>
 +
#define SQUARE(n) (n*n)
 +
 +
static uint32_t square(uint32_t n)
 +
{
 +
return n*n;
 +
}
 +
 
</source>
 
</source>
 +
 +
* 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.

Latest revision as of 11:25, 7 January 2014

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