Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a pointer variable to a const int in C++?

I'm wondering if anyone can explain the following to me: If I write

int i = 0;
float* pf = i;

I get a compile error (gcc 4.2.1):

error: invalid conversion from ‘int’ to ‘float*’

Makes sense - they are obviously two completely different types. But if instead I write

const int i = 0;
float* pf = i;

It compiles without error. Why should the 'const' make a difference on the right hand side of the assignment? Isn't part of the idea of the 'const' keyword to be able to enforce type constraints for constant values?

Any explanation I have been able to come up with feels kind of bogus. And none of my explanations also explain the fact that

const int i = 1;
float* pf = i;

fails to compile. Can anyone offer an explanation?

like image 808
John Avatar asked May 12 '10 23:05

John


People also ask

How do you declare a pointer to an integer constant?

We declare a pointer to constant. First, we assign the address of variable 'a' to the pointer 'ptr'. Then, we assign the address of variable 'b' to the pointer 'ptr'. Lastly, we try to print the value of 'ptr'.

Can we declare a pointer variable as constant in C?

We can create a pointer to a constant in C, which means that the pointer would point to a constant variable (created using const). We can also create a constant pointer to a constant in C, which means that neither the value of the pointer nor the value of the variable pointed to by the pointer would change.

Can a pointer point to a const?

In the pointers to constant, the data pointed by the pointer is constant and cannot be changed. Although, the pointer itself can change and points somewhere else (as the pointer itself is a variable).

Which constant value can be assigned to a pointer variable?

Pointer to constant As the name itself indicates, the value of the variable to which the pointer is pointing, is constant. In other words, a pointer through which one cannot change the value of the variable to which it points is known as a pointer to constant.


1 Answers

Your second example simply happens to be covered by the conversion rules as specified in §4.10/1 (C++03):

A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to zero. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of pointer to object or pointer to function type.

like image 93
Georg Fritzsche Avatar answered Sep 18 '22 11:09

Georg Fritzsche