Goldname Goldname - 1 year ago 74
C Question

Why does const char *foo = "Hello"; compile but not const int *foo = 5;?

Correct me if I am wrong, but I had assumed this line of code:

const char *foo = "Hello";

Meant that an array of chars filled with "Hello" are created somewhere on the stack, and foo is a pointer to it. In that case, I don't understand why this line of code gives an "invalid conversion from 'int' to 'const int*'

const int *foo = 5;

Won't it just create an integer of 5 somewhere on the stack and have foo point to it?

Answer Source

Because "Hello" is a string literal of type char [N] (in C) and const char[N] (in C++), which decays to a type char* (in C) or const char* (in C++), same as the pointer you are binding it to. On the other hand, 5 is a rvalue and its type is an int, so you cannot bind it to a pointer of type const int*.

You may find this useful.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download