23

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

?

Community
  • 1
  • 1
erkangur
  • 2,048
  • 5
  • 21
  • 31

4 Answers4

41

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.

Michael
  • 54,279
  • 5
  • 125
  • 144
  • 2
    ` 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. – Rüppell's Vulture May 05 '13 at 19:16
  • 4
    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. – shashwat Jun 18 '14 at 11:50
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.

Lucas Jones
  • 19,767
  • 8
  • 75
  • 88
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.

Timo Tijhof
  • 10,032
  • 6
  • 34
  • 48
swegi
  • 4,046
  • 1
  • 26
  • 45
  • 2
    @Michael: Nope, at least not if gcc is used. "foo.c:2: error: variably modified ‘arr’ at file scope" – swegi Jul 09 '10 at 21:51
  • 3
    You are correct. I missed the C tag on the question. What I said holds true for C++. – Michael Jul 09 '10 at 22:27
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

µBio
  • 10,668
  • 6
  • 38
  • 56