Scope of #define

G

Guest

What is the scope of #define statement?
Say we have an inlude file as follows

---MyInclude1.h---
#ifndef MYINCLUDE1_H
#define MYINCLUDE1_H

#define EXAMPLE1 1000
#define EXAMPLE2 2000
#define EXAMPLE3 "Hello World"

#endif
---End of MyInclude1.h---

---MyInclude2.h---
#ifndef MYINCLUDE2_H
#define MYINCLUDE2_H

#define EXAMPLE1 "ABC"
#define EXAMPLE2 "DEF"
#define EXAMPLE3 3000

#endif
---End of MyInclude2.h---

If we include the MyInclude1.h and MyInclude2.h into my main program what
would be the value of EXAMPLE1,2,3 ?
 
V

Victor Bazarov

Kay said:
What is the scope of #define statement?

Don't you mean, what's the lifetime of the macro it defines? If so,
it's from the point of definition until the #undef for the same macro
or until the end of the translation unit preprocessing.
Say we have an inlude file as follows

---MyInclude1.h---
#ifndef MYINCLUDE1_H
#define MYINCLUDE1_H

#define EXAMPLE1 1000
#define EXAMPLE2 2000
#define EXAMPLE3 "Hello World"

#endif
---End of MyInclude1.h---

---MyInclude2.h---
#ifndef MYINCLUDE2_H
#define MYINCLUDE2_H

#define EXAMPLE1 "ABC"
#define EXAMPLE2 "DEF"
#define EXAMPLE3 3000

#endif
---End of MyInclude2.h---

If we include the MyInclude1.h and MyInclude2.h into my main program what
would be the value of EXAMPLE1,2,3 ?

What would be the value where? How do you include?

V
 
A

Ali Cehreli

What is the scope of #define statement?

It is a simple text replacement. There is no scope at all.
Say we have an inlude file as
follows

---MyInclude1.h---
#ifndef MYINCLUDE1_H
#define MYINCLUDE1_H

#define EXAMPLE1 1000
#define EXAMPLE2 2000
#define EXAMPLE3 "Hello World"

#endif
---End of MyInclude1.h---

---MyInclude2.h---
#ifndef MYINCLUDE2_H
#define MYINCLUDE2_H

#define EXAMPLE1 "ABC"
#define EXAMPLE2 "DEF"
#define EXAMPLE3 3000

#endif
---End of MyInclude2.h---

If we include the MyInclude1.h and MyInclude2.h into my main program
what would be the value of EXAMPLE1,2,3 ?

You would be redefining the macros.

By the way, your compiler must have an option to show you what the
preprocessed output looks like. With g++, it is -E:

g++ -E mycode.cppb

Try the following definitions instead of macros:

int const example1 = 1000;
int const example2 = 2000;
char const * const example3 = "Hello World";

Ali
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,172
Messages
2,570,934
Members
47,477
Latest member
ColumbusMa

Latest Threads

Top