Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ Macros Text-based Essentially just search-and-replace

Similar presentations


Presentation on theme: "C++ Macros Text-based Essentially just search-and-replace"— Presentation transcript:

1 C++ Macros Text-based Essentially just search-and-replace
Can be the source of subtle bugs Use is not recommended in modern C++

2 C++ Macros #define INCI(i) do { int a=0; ++i; } while(0)
Handled by the pre-processer (not the compiler) Not same as function definitions (e.g. no type for parameter)

3 a is the same name as local variable in the macro!
#define INCI(i) do { int a=0; ++i; } while(0) INCI(k): do { int a=0; ++k; } while(0) OKAY INCI("cat"): do { int a=0; ++"cat"; } while(0) BAD INCI(a): do { int a=0; ++a; } while(0) BAD a is the same name as local variable in the macro!

4 Macros Expansion #define INCI(i) do { int a=0; ++i; } while(0) int main(void) { int a = 4, b = 8; INCI(a); INCI(b); printf("a is now %d, b is now %d\n", a, b); return 0; } int main(void) { int a = 4, b = 8; do { int a=0; ++a; } while(0); do { int a=0; ++b; } while(0); printf("a is now %d, b is now %d\n", a, b); return 0; } // a is now 4, b is now 9 a is unchanged because it was “captured” by the scope of the local a in the macro

5 Possible Fix #define INCI(i) do { int INCIa=0; ++i; } while(0)
INCIa is a name that is unlikely to be used by other code … but no guarantees!!


Download ppt "C++ Macros Text-based Essentially just search-and-replace"

Similar presentations


Ads by Google