So from my understanding pointer variables point to an address. So, how is the following code valid in C++?
char* b= "abcd"; //valid
int *c= 1; //invalid
See Question&Answers more detail:osSo from my understanding pointer variables point to an address. So, how is the following code valid in C++?
char* b= "abcd"; //valid
int *c= 1; //invalid
See Question&Answers more detail:osThe first line
char* b= "abcd";
is valid in C, because "string literals", while used as initializer, boils down to the address of the first element in the literal, which is a pointer (to char
).
Related, C11
, chapter §6.4.5, string literals,
[...] The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type
char
, and are initialized with the individual bytes of the multibyte character sequence. [...]
and then, chapter §6.3.2.1 (emphasis mine)
Except when it is the operand of the
sizeof
operator, the_Alignof
operator, or the unary&
operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.
However, as mentioned in comments, in C++11
onwards, this is not valid anymore as string literals are of type const char[]
there and in your case, LHS lacks the const
specifier.
OTOH,
int *c= 1;
is invalid (illegal) because, 1
is an integer constant, which is not the same type as int *
.