Solved

const in C++

Posted on 2004-09-27
9
776 Views
Last Modified: 2012-08-13
I am trying to understand the exact semantics of const in C++. So I wrote the following program:

#include <iostream>

using namespace std;

int main() {
    const int x = 2;
    int *p = (int *)&x;
    *p = 1;
    cout << x << endl;
}

My expectation was that the program should print 1 but it prints 2. Is this correct behavior according to the C++ standard? Surely when the programmer has explicitly overridden the constness of a variable, the compiler must obey. But this does not seem to be the case. Are there any explanations? I am using "g++ -g test.cpp" to compile the program.
0
Comment
Question by:priyendra
9 Comments
 
LVL 48

Accepted Solution

by:
AlexFM earned 125 total points
ID: 12159210
Why does this happen? This is Assembly code produced by C++ compiler:

13:       const int x = 2;
00401798   mov         dword ptr [ebp-4],2
14:       int *p = (int *)&x;
0040179F   lea         eax,[ebp-4]
004017A2   mov         dword ptr [ebp-8],eax
15:       *p = 1;
004017A5   mov         ecx,dword ptr [ebp-8]
004017A8   mov         dword ptr [ecx],1
16:       cout << x << endl;
004017AE   push        offset @ILT+195(std::endl) (004010c8)
004017B3   push        2
...

push 2 - compiler passes hard-coded 2 instead of c to cout. I tested with VC++ 6.0 and 7.1 with the same result. Since VC++ 7.1 is almost 100% standard compliant, I guess this is correct behaviour.
Compiler doesn't show error message or warning because it cannot recognize constness violation done using pointer.
0
 
LVL 5

Expert Comment

by:info_expert
ID: 12160039
Hi,

Because the association of a const variable is with the name of the variable and not the address of variable, at compile time.

So the no matter you try to modify it by other methods, it will remain same.

Regards.
0
 
LVL 5

Expert Comment

by:info_expert
ID: 12160051
Again I emphasize on my words "compile time" binding of variable name (x) with hard coded (const) value.
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 12160084
Debugger shows that after the line:
*p = 1;
x value is changed to 1. However, compiler doesn't use this value and replaces it with hard-coded initial value 2:
cout << 2 << endl;          // in Assembly code
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 

Expert Comment

by:s_senthil_kumar
ID: 12161120
That's because you've used a C style cast, which doesn't care about const-ness. Try it with a static cast.
int main() {
    const int x = 2;
    int *p = static_cast<int *>(&x);
    *p = 1;
    cout << x << endl;

     return 1;
}

The compiler will now say that it can't cast from const int * to int *. Of course, you can override that with a const_cast, but that's beside the point.  You can cast to const int *, but then the compiler will disallow *p = 1

Moral of the story : Never use C style casts unless they're absolutely necessary.
0
 

Expert Comment

by:bhattmayank
ID: 12161587
Yes "s_senthil_kumar" is right, try it out what he said. and u will find why it was like this.
even in the symbol tables i guess the X will have the value 2 and though as per the assembly shown above it's just reading the symbol table and try to print the associated value of x in symbole table !
|+|ayank
0
 
LVL 4

Expert Comment

by:Farshid-Zaker
ID: 12162837
Const is an early binding element. It means it is replaced by its value at compile time. & and * operators are simulated on const elements at compile time and they return virtual values, not really the address of a const variable!
0
 
LVL 12

Expert Comment

by:stefan73
ID: 12167040
Hi priyendra,

A const does have an address which you used - such as for passing const argument by reference.

but since the compiler knows this is a constant, it assumes it can use the value directly.

Cheers!

Stefan
0
 
LVL 9

Expert Comment

by:jhshukla
ID: 12174075
>> but since the compiler knows this is a constant, it assumes it can use the value directly
true. should try with const members in classes and see what the compiler does.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now