Stumbled on this row of c code but was unsure if it is valid or not. What does it do? What type will the variable have?
const VARNAME = "String of text";
Curiously, I wasn't expecting this to compile, but it does. However, compiler doesn't like it too much:
..\main.c:4:7: warning: type defaults to 'int' in declaration of 'VARNAME'
..\main.c:4:17: warning: initialization makes integer from pointer without a cast
So it does take int as default type, and thus VARNAME has a pointer value, since a string is a pointer (which later could be cast as char*).
This works perfectly (on a Intel IA32 machine):
#include<stdio.h>
const VARNAME = "String of text";
int main()
{
printf("%s\n", (char*)VARNAME);
return 0;
}
But I personally wouldn't use such implicit typing. As explained on the comments below:
it's even dangerous since sizeof(int) might be smaller than sizeof(char*)
What GCC tries to do is:
VARNAME
with the default type, that is int
;int
contain a pointer to the character constant.On my machine, it doesn't compile, probably because int
is 32 bits and pointers are 64 bits wide.
a.c:1: error: initializer element is not computable at load time
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With