Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 

?

like image 559
erkangur Avatar asked Jul 09 '10 21:07

erkangur


People also ask

What is the difference between macro and constant in C?

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.

What is the difference between a macro and a variable?

Variables can have types like Integer or Character. Whereas macros are not variables at all, they are special C directives which are pre-processed before the compilation step is carried out by the compiler to create the object file (binary code of the program).

What is a macro constant in C?

Description. In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables.

What is the difference between a #define constant and const?

The difference is that #define is processed by the preprocessor doing what amounts to simple text replacement. Const values defined like this are not visible for the actual compiler, while a variable defined with the const modifier is an actual typed "variable" (well not really that variable).


2 Answers

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.

like image 126
Michael Avatar answered Sep 20 '22 18:09

Michael


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.

like image 36
Lucas Jones Avatar answered Sep 20 '22 18:09

Lucas Jones