Search code examples
cstructuredefinitionredefinition

Structure variable initialization/definition in one go after variable declaration is done


Can we define structure variable after its declaration or definition in one go? All together in single braces like

asd = {21,'H'};

Any particular reason if it cannot be done, since it can be defined in same line where it is being declared e.g.: struct asd = {21,'H'}; ?

struct test
{
    int a;
    char b;
}asd;  

asd = {21,'H'};   // error: expected an expression

Asked for C programming.


Solution

  • The explicit type cast is required:

    struct test
    {
        int a;
        char b;
    } asd;  
    
    asd = (struct test){21,'H'};
    

    This code is roughly equivalent to the following one:

    const struct test initialiser = {21,'H'};
    ... 
    asd = initialiser;
    

    The difference is that the compiler has an option to optimise the assignment of a value to the asd variable using assembler instructions with immediate values when such optimisation is more efficient than const structure copy initialisation.

    As a 'side' effect this syntax is valid in both C and C++