Const vs Define

Apr 15, 2012 at 3:30pm
I know that #define is a preprocessor directive, so it doesn't take up any memory. All I know about const is that when you define a constant variable, you can't change the value later in the code.

Based on that, what use would there be for using const? Couldn't you just define a constant variable as a normal one, and just not change anywhere in the code?
Apr 15, 2012 at 3:39pm
const is the replacement of define in C++, define is for C.

And const helps in many situations when you want to hold some variables unchanged; for example, if you want to pass a variable by reference, having a const beside it is a protection for yourself against changing it without knowing it.

And const are easier to use because they're within the code, unlike define, where it usually lies at the beginning of your code. It's recommended to use #define for global constants, like Pi and other physics constants.

In classes, suffix const for methods mean that the method isn't allowed to change the class.

In classes, a return const reference value is a solution to give the user the value without copying it, and to prevent him from changing it.

There are dozens more... is this good enough for you?
Apr 15, 2012 at 3:48pm
Thank-you, that helps a lot.
Apr 15, 2012 at 4:02pm
closed account (zb0S216C)
In addition to The Destroyer's post, #defined constants will not follow the rules of scoping. This means that #defined constants will not be a part of any scope, not even the global scope. For instance:

1
2
3
4
namespace My_Namespace
{
    #define CONSTANT 10
}

Here, CONSTANT is not within the scope of My_Namespace. The reason behind this is because a #defined constant doesn't have a place within the symbol table (a place where all identifiers of a program are stored). Before the code is compiled, all occurences of CONSTANT will be replaced with 10, followed by the removal of CONSTANT. Consequently, the compiler will never see the name CONSTANT.

Unlike #defined constants, const objects are called symbolic constants, and have a place within the symbol table. This allows them to reside within a scope of a class, function, or namespace.

Wazzak
Last edited on Apr 15, 2012 at 5:55pm
Apr 15, 2012 at 4:20pm
I think it's important to note that #define is not completely deprecated in C++, it's just not recommended in most cases. You have to use it at some level if you want conditional compilation.
Apr 15, 2012 at 4:38pm
#define is best used for header inclusion guards and macros (when necessary). Conditional compilation can be achieved via compiler flags (-D) rather than having #defines in the code.
Topic archived. No new replies allowed.