What is the difference between macro constants and constant variables in C?

Possible duplicate:
"static const" vs "#define" in C

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

What changes when recording,

#define A 8 

and

 const int A = 8 

?

+18
source share
4 answers

Macros are processed by the preliminary processor - the preliminary processor replaces the text in the source file, replacing all events "A" with the letter 8.

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

For real compiled code, with any modern compiler, there should be zero performance difference between them.

+27
source

Macro-defined constants are replaced by a preprocessor. Constant variables are controlled in the same way as 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; 

Will appear as:

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

:)

In practice, the main thing is that change is an area: constant variables obey the same definition rules as standard variables in C, which means that they can be limited or possibly redefined in a specific block without leakage - this is similar to the situation local and global variables.

+7
source

In C you can write

 #define A 8 int arr[A]; 

but not:

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

if I remember the rules correctly. Note that both will work in C ++.

+4
source

First, the first will cause the preprocessor to replace all occurrences of A with 8 before the compiler does anything, and the second will not turn on the preprocessor

+1
source

Source: https://habr.com/ru/post/945356/


All Articles