sivabudh
sivabudh

Reputation: 32635

C++ const : how come the compiler doesn't give a warning/error

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.

Upvotes: 4

Views: 278

Answers (4)

Alexander Gessler
Alexander Gessler

Reputation: 46607

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)

Upvotes: 0

Patrick
Patrick

Reputation: 23619

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.

Upvotes: 2

Pete
Pete

Reputation: 10680

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

Upvotes: 2

JaredPar
JaredPar

Reputation: 754695

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

Upvotes: 12

Related Questions