pacopepe222
pacopepe222

Reputation: 191

Weird initialization in C

I have this piece of code and i don't know how it works

#include <stdio.h>

int main(void)
{
    int numero = ({const int i = 10; i+10;});

    printf("%d\n", numero); // Prints 20

    return 0;
}

Why if i delete the second part (i+10;), the compiler gets an error? Why are the brackets necessary?

Thank you ^^!

Upvotes: 9

Views: 186

Answers (1)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506837

It's a GCC statement expression. It executes the statements in it, and returns the value evaluated in the last statement. Thus numero is initialized to 20. If you delete the second part, there is no expression as the last statement, so it can't get a value from the statement expression.

The braces are necessary to disambiguate it from ordinary C parenthesized expressions.

Upvotes: 13

Related Questions