tags:

views:

164

answers:

4

Possible Duplicate:
Sell me on using const correctness

In C (and I guess C++ as well), is there any particular reason to declare a variable const other than to prevent yourself from modifying it by mistake later on? Are const variables treated differently at compile time other than the fact that they aren't allowed to be modified?

Edit: I understand the obvious optimizations that come from declaring a *ahem* constant as const, and the whole const method thing makes sense in C++, but how about declaring a function argument as const in C?

A: 

http://stackoverflow.com/questions/212237/constants-and-compiler-optimization-in-c this must answer your question

slayerIQ
+1  A: 

I use it to declare application constants, which is a matter of style and readability. Instead of littering your program with magic numbers -- that is, undocumented or opaque values -- you can use const variables to make your code a bit more understandable. Consider the difference between

setStatus(207);

versus

setStatus(HttpClient::HTTP_MULTISTATUS);

The first one placed more of a burden on the reader, to know specific HTTP status codes. The second one just requires you to read the name of the constant to understand what's happening.

Jesse Dhillon
I'd actually consider this as a counter example for the use of constants. In case of very well known numbers constants seem to merely obscure the real value.
x4u
I don't think that HTTP 400 is very well known, but I've updated it with a better example.
Jesse Dhillon
+4  A: 

const correctness is one of the most important concepts to understand for C++ development. The C++ FAQ has an excellent description and several examples. In general, using the const keyword prevents your const objects from being mutated.

Sam Miller
+2  A: 

There are couple of uses of 'const' at compile time.

  1. The keyword const and volatile are type specifiers. They are called fondly enought as cv-qualifiers.

e.g. int const x = 0; // x is non-modifiable lvalue

  1. These are the only declaration specifiers that can occur in declarators e.g.

int * const p = 0; // here const applies to p

  1. Here is a short program to clarify some uses of 'const'

    int const maxpath = 255; // non modifiable lvalue, also specifies internal linkage

    struct A{ int const x; // non modifiable lvalue int y; void f() const {y = 2;} // error, type of 'this' is A const *, can't modify 'x' and 'y'

    A():x(0){}
    

    };

    int main(){ const int * const p = NULL; // p is a const pointer to const int }

  2. cv-qualifier on functions also participate in overloading.

  3. references to const (as against references to non-const) can bind to appropriate rvalues

Chubsdad