C
lets me use char
pointers and arrays interchangeably often enough that I often think of them as completely interchangeable. But the following code demonstrates this is not true. Can anyone please explain why the initialization of const char d[]
with the ternary operator, in the code below, is illegal?
/* main.c */
#include <stdio.h>
int main()
{
const char* a = "lorem";
const char b[] = "ipsum";
int* p;
const char* c = ( *p ? "dolor" : "sit" );
const char d[] = ( *p ? "amet" : "consectetur" ); // Why am I an error?
return 0;
}
Compilation:
> gcc -g main.c
main.c: In function \u2018main\u2019:
main.c:10:20: error: invalid initializer
const char d[] = ( *p ? "amet" : "consectetur" ); // Why am I an error?
Related question: in case my terminology has been imprecise here: what is the correct term to describe const char d[]
? Is it an array? A variable-length array? Something else? It is not considered a pointer - true?
Edit: I believe this question is not answered by Array initialization with a ternary operator?
RE: the referenced question, I believe the premise is slightly different. E.g. the accepted answer explains that { 1, 2 };
(or { 'a', 'b' );
) are not valid C
expressions, which I know already and accept. However "amet";
and "consectetur";
are valid C
expressions.