1. 程式人生 > >The Difference between #define and const in C/C++

The Difference between #define and const in C/C++

The Difference between #define and const in C/C++

I was recently asked an interesting question by one of my friends who is currently learning to program in C & C++. He wanted to know what the differences were between the #define pre-processor command and a constant variable. For those unfamiliar with C the syntax for each of these types is as follows:

Both of these lines of code create a “constant” which can be used in other parts of the code by the reference NAME. Both lines seem to perform almost identical operations, so why do we need both of them?

The main difference between them is how they are processed by the compiler/program. As indicated by the leading ‘#’ character the #define command is processed during pre-processing of the program.

What does this mean exactly?

Well when you first run gcc (or whatever your choice of compiler) it goes through the given file and one of the first things it does is look at all of the #define symbols and parses through the entirety of the code and physically replaces the text NAME with the text VALUE wherever it shows up. Note that this is non-discriminatory the compiler will replace any occurrence of NAME (outside of string literals) with VALUE. This also means that if VALUE is not syntactically correct (A string without quotes for instance) the compiler will throw an error later on.

As a quick example lets declare a string by using a #define symbol:

When this code is run there will be a variable in memory called test_string and it will have the value Hello World!. Note that if the quotes around hello world were not there in the define statement for TEST_STRING the compiler would have thrown a syntax error when processing the next line.

For those of you wondering yes, that does mean that you can do things like this:

which will actually compile and when run print Hello World to standard output.

This plethora of functionality is in direct contrast to how a constant variable works, which is exactly like a normal variable except that the value cannot change. The variable is processed at compile time and there is no interesting text replacement feature.

Now the question becomes, why would you ever want to do this?

Hello World!Lets say that in several places in your code you needed to call a function that acted like a generator and returned the next value in the series. If you were to use #define, you could set the define value to the function call like so: #define NEXT_VALUE generator() and whenever you put NEXT_VALUE in your file it would actually be a function call to produce the next generator value. However if you were to assign this value to a constant: const int value = generator(); the value of the constant would always be the first generator value. In this way #define allows you to have a changing “constant” that is referred to with the same symbol repeatedly.