Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this nameless variable? C

Tags:

c

Take this code

int main() {
     int *p = &(int){2};
}

What is this? &(int){2} A variable without a name? What's the point of a nameless variable in C? How does the compiler know to keep it on the stack if it's not assigned to a name?

Furthermore, if I declare a nameless value such as

int main() {
   (int){3};
}

is there a way to get the address of this nameless variable back in a fully portable way? (fully portable as in, it's gonna work on every platform no matter how the stack is arranged)

After years of coding in C I had no idea you could declare nameless variables like that. Is there a reason you would want to use this over regular named variables?

like image 296
aganm Avatar asked Feb 20 '26 15:02

aganm


1 Answers

This is called a compound literal. Its lifetime is the same as a local variable declared in the same scope.

One common use is to assign all values of a struct after it has been initialized:

struct s {
  int a;
  float b;
};

struct s s1;
s1 = (struct s){3, 4.0};

Or to pass its address to a function that requires a pointer to a valid object, but you don't plan on using that object after the function has returned:

int x[5];
memcpy(x, (int[5]){3,4,5,6,7}, sizeof(int[5]));
like image 80
dbush Avatar answered Feb 22 '26 04:02

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!