25

Possible Duplicate:
“static const” vs “#define” in C

I started to learn C and couldn't understand clearly the differences between macros and constant variables.

What changes when I write,

#define A 8 

and

const int A = 8 

?

0

4 Answers 4

45

Macros are handled by the pre-processor - the pre-processor does text replacement in your source file, replacing all occurances of 'A' with the literal 8.

Constants are handled by the compiler. They have the added benefit of type safety.

For the actual compiled code, with any modern compiler, there should be zero performance difference between the two.

Sign up to request clarification or add additional context in comments.

2 Comments

` there should be zero performance difference between the two`--Thanks for making it so clear.Moments before I read in a wretched book that I have that says that the latter is slower than using the macro.
But using macros sometimes can increase size of object file. Suppose you have a very large string stored in a macro, pre-processor will replace all the occurrence of this string by its value before compiling, resulting in comparatively larger object file.
11

Macro-defined constants are replaced by the preprocessor. Constant 'variables' are managed just like regular variables.

For example, the following code:

#define A 8 int b = A + 10; 

Would appear to the actual compiler as

int b = 8 + 10; 

However, this code:

const int A = 8; int b = A + 10; 

Would appear as:

const int A = 8; int b = A + 10; 

:)

In practice, the main thing that changes is scope: constant variables obey the same scoping rules as standard variables in C, meaning that they can be restricted, or possibly redefined, within a specific block, without it leaking out - it's similar to the local vs. global variables situation.

Comments

6

In C, you can write

#define A 8 int arr[A]; 

but not:

const int A = 8; int arr[A]; 

if I recall the rules correctly. Note that on C++, both will work.

2 Comments

@Michael: Nope, at least not if gcc is used. "foo.c:2: error: variably modified ‘arr’ at file scope"
You are correct. I missed the C tag on the question. What I said holds true for C++.
2

For one thing, the first will cause the preprocessor to replace all occurrences of A with 8 before the compiler does anything whereas the second doesn't involve the preprocessor

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.