Overselling #defined consts?

Does the current cplusplus.com tutorial on consts oversell #define as a way of defining consts?

From http://www.cplusplus.com/doc/tutorial/constants/

Defined constants (#define)

You can define your own names for constants that you use very often without having to resort to memory-consuming variables, simply by using the #define preprocessor directive. Its format is: ...


Declared constants (const)

Here, pathwidth and tabulator are two typed constants. They are treated just like regular variables except that their values cannot be modified after their definition.

...


What concerns me is the suggestion that #defines are better because they take up less space. From what I understand, the optimizer is not forced to put a value in the read-only data segment and use it from there if it doesn't want to.

Am I reading the article wrong?

Andy

PS This exciting program

1
2
3
4
5
6
7
8
9
10
const int a = 100;

int test1(int m) {
    return (a * m);
}

int main() {
    int m = 2;
    return test1(m);
}


compiles to (VC++ /O2)

00401000 B8 C8 00 00 00   mov         eax,0C8h 
00401005 C3               ret  


i.e. the same as if I'd written

1
2
3
int main() {
    return 200;
}

Last edited on
I agree, it would be good if the article explicitly suggested using const over #define (it could say that type safety is more important than the minimal difference in memory usage and speed, especially when often the compiler will optimise const values away). Even more important is the lack of a section for enumerated constants. IMO enum should be preferred over both const and #define for numeral constants.
Last edited on
closed account (3hM2Nwbp)
With the advent of enum classes, now there are even more advantages (#1 type safety) to using them as compared to preprocessor hackery.
FYI: Enums are discussed in the tutorial (just on another page)
http://cplusplus.com/doc/tutorial/other_data_types/
Topic archived. No new replies allowed.