Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this c code row do? (const VAR = "string";)

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";
like image 934
ihatetoregister Avatar asked Feb 22 '12 12:02

ihatetoregister


2 Answers

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*)

like image 176
m0skit0 Avatar answered Sep 30 '22 07:09

m0skit0


What GCC tries to do is:

  1. Make a constant VARNAME with the default type, that is int;
  2. make this constant 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
like image 41
Fred Foo Avatar answered Sep 30 '22 07:09

Fred Foo