Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird initialization in C

Tags:

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 ^^!

like image 393
pacopepe222 Avatar asked May 23 '10 18:05

pacopepe222


People also ask

What are the two types of array initialization?

There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.

Does C automatically initialize arrays to 0?

An array may be partially initialized, by providing fewer data items than the size of the array. The remaining array elements will be automatically initialized to zero.

What is runtime initialization in C?

Run time Array initialization Using runtime initialization user can get a chance of accepting or entering different values during different runs of program. It is also used for initializing large arrays or array with user specified values. An array can also be initialized at runtime using scanf() function.

What is C++ initialization?

Variable initialization in C++ There are two ways to initialize the variable. One is static initialization in which the variable is assigned a value in the program and another is dynamic initialization in which the variables is assigned a value at the run time.


1 Answers

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.

like image 63
Johannes Schaub - litb Avatar answered Sep 28 '22 03:09

Johannes Schaub - litb