Use of #undef?

What's the difference if I do this

1
2
  #define pi 3.14
  #define pi 3.142 


rather than this

1
2
3
  #define pi 3.14
  #undef pi
  #define pi 3.142 


When I print out pi it's as if it's overwritten , does that mean I don't need to use #undef? Can someone give me an example of when I would need it and redefining it wouldn't work.

Thanks
In the case of a constant such as pi, it's better to use a const rather than #define
const double PI = 3.1415926535897932385;

#define has other uses, one is in macros, another is conditional compilation.
For example:
1
2
3
4
5
6
7
8
9
10
11
#define DEBUG 1

#ifdef DEBUG
    cout << "message 1" << endl;
#endif

#undef DEBUG

#ifdef DEBUG
    cout << "message 2" << endl;
#endif 


Here, the state of DEBUG can be used to control which lines of code are actually compiled. By changing a single line of code, e.g. changing line 1 into a comment, the program can be effectively changed in many places in one go.
#undef can be used to limit the scope of the define, in a similar way to braces { } which can limit the scope of other identifiers.
Topic archived. No new replies allowed.