#define and just declaration

What's the difference between

#define BLAH_BLAH_BLAH 123

and

int BLAH_BLAH_BLAH = 123;
?

Thanks.
A define directive is used during compile time, almost like a variable, and is treated as a constant at run time. A variable is around during run time, in memory, rather than being a constant value.

1
2
3
#define NUM 5

cout << NUM;


will turn into:
 
cout << 5;


Whereas:
1
2
3
const int NUM = 5;

cout << NUM;


Will store the value of NUM in RAM at run time.
With the second version I can do:

BLAH_BLAH_BLAH = 124;

I can't do that with the first.

Now, the real question is: What's the difference between "#define BLAH 123" and "const int BLAH = 123;"? ;-)

closed account (DSLq5Di1)
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.7
Thanks everyone!
@PanGalactic If the compiler optimizes const int BLAH by placing the value directly into the machine instructions, then not much.
Last edited on
@shacktar:

1
2
3
4
5
namespace foo
{
#define BLAH_1 123
const int BLAH_2 = 123;
}


Notice a difference here?
I was assuming something like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
#define BLAH_1 123
const int BLAH_2 = 123;

#include <iostream>
using namespace std;

int main()
{
    cout<<BLAH_1<<endl;
    cout<<BLAH_2<<endl;

    return 0;
}


In the above case, the compiler can optimize for memory and never put BLAH_2 into RAM. I didn't stop to think about scoping, which of course is the major difference :)
Last edited on
Topic archived. No new replies allowed.