tags:

views:

140

answers:

4

Really simple question about C++ constness.

So I was reading this post, then I tried out this code:

int some_num = 5;
const int* some_num_ptr = &some_num;

How come the compiler doesn't give an error or at least a warning?

The way I read the statement above, it says:

Create a pointer that points to a constant integer

But some_num is not a constant integer--it's just an int.

+13  A: 

The problem is in how you're reading the code. It should actually read

Create a pointer to an integer where the value cannot be modified via the pointer

A const int* in C++ makes no guarantees that the int is constant. It is simply a tool to make it harder to modify the original value via the pointer

JaredPar
Perfect, thank you for clarification.
ShaChris23
+2  A: 

I agree with Jared Par's answer. Also, check out the C++ FAQ on const correctness.

Pete
http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.5 -> Helped me understand in a jiffy :)
legends2k
+2  A: 

The const keyword just tells the compiler that you want some stricter checking on your variable. Castring a non const integer to a const integer pointer is valid, and just tells the compiler that it should give an error if you try to change the value of the contents of the const-pointer.

In other words, writing

*some_num_ptr = 6;

should give an error since the pointer points to a const int.

Writing

some_num = 7;

remains valid of course.

Patrick
A: 

int* ptr; just says you can't change the valued pointed to by ptr through ptr. The actual value might still be changed by other means.

(the actual reason the compiler doesn't warn is that casts from T* to const T* are implicit)

Alexander Gessler