These two forms of the same variable, when defined within scope of a function block should, I would think, have identical scope, i.e. within the function blocks {...}
where they are defined:
char str1[] = "int_1 < int_2";
char *str1 = "int_1 < int_2";
But my observation is that the char *
lives beyond function scope, while the char []
ceases to exist. The symbol name str1
in both cases points to the location in memory where the variable is created, so why does one seem to live beyond the function, while the other does not? The following code can be used to test this behavior: (Changing #define
from 0
to 1
selects one form over the other for illustration.)
Note also that that although the static
modifier could be used to modify scope, it is purposely not used here to observe behavior without it.
#define DO (1) //define as either 1 or 0
char * compare_int(int x1, int x2);
int main(void)
{
int a = 0;
int b = 0;
int c = '\n';
srand(clock()/CLOCKS_PER_SEC);
while(c != 'q')
{
a = rand()%3;
b = rand()%3;
printf("%s\n( enter 'q' to exit. )\n\n", compare_int(a, b));
c = getchar();
}
return 0;
}
char * compare_int(int x, int y)
{
printf("%d %d\n", x, y);
#if(DO)
char str1[] = "int_1 < int_2";
char str2[] = "int_1 == int_2";
char str3[] = "int_1 > int_2";
#else
char *str1 = "int_1 < int_2";
char *str2 = "int_1 == int_2";
char *str3 = "int_1 > int_2";
#endif
return x < y ? (str1) : x == y ? (str2) : (str3);
}
I have read this, and it does answer some key parts to this question, but comments on any UB in my code, and/or references to C99 or newer standard pointing to paragraph(s) that make the distinctions between these two forms would also be appreciated.