Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between #define and const? [duplicate]

Possible Duplicates:
Why would someone use #define to define constants?
difference between a macro and a const in c++
C++ - enum vs. const vs. #define

What is the difference between using #define and const for creating a constant? Does any have a performance advantage over the other? Naturally I prefer using the const but I'm going to consider the #define if it has suitable advantages.

like image 238
afaolek Avatar asked Jun 22 '11 15:06

afaolek


People also ask

What is the definition of the difference between?

The difference between two things is the way in which they are unlike each other.

What is difference between this & these?

This and these are used to point to something near you. For a singular thing, use this. For a plural thing, use these.

What is difference between among and between?

The most common use for among is when something is in or with a group of a few, several, or many things. The most common use of between is when something is in the middle of two things or two groups of things. It is sometimes used in the phrase in between.

What is the difference between this or it?

The main difference between the two is that 'it' is a third-person singular personal pronoun, and 'this' is a demonstrative determiner and pronoun. Because of this difference in grammatical categories, they can perform different roles in a sentence.


2 Answers

The #define directive is a preprocessor directive; the preprocessor replaces those macros by their body before the compiler even sees it. Think of it as an automatic search and replace of your source code.

A const variable declaration declares an actual variable in the language, which you can use... well, like a real variable: take its address, pass it around, use it, cast/convert it, etc.

Oh, performance: Perhaps you're thinking that avoiding the declaration of a variable saves time and space, but with any sensible compiler optimisation levels there will be no difference, as constant values are already substituted and folded at compile time. But you gain the huge advantage of type checking and making your code known to the debugger, so there's really no reason not to use const variables.

like image 197
Kerrek SB Avatar answered Sep 22 '22 06:09

Kerrek SB


#define creates an entity for substitution by the macro pre-processor, which is quite different from a constant because depending on what you define it will or will not be treated as a constant. The contents of a #define can be arbitrarily complex, the classic example is like this:

#define SQR(x) (x)*(x) 

Then later if used:

SQR(2+3*4) 

That would be turned into:

(2+3*4)*(2+3*4) 
like image 31
zippy Avatar answered Sep 23 '22 06:09

zippy