0

Got a doubt in struct variable assignment.

struct udata
{
    char name[50];
    int num;
    char ch;
};

void main()
{
    struct udata a = {"ram", 20, 'a'};
    struct udata b;
    //b = {"ashok", 10, 'c'}; - illegal
    b = a;
}

In above code b = {"ashok", 10, 'c'}; is giving compilation error but its accepting b = a;. I hope both are similar kind of assignment, but I dont know why its not accepting first one. Can someone explain me why it is so ?

Note : I am compiling in a fedora gcc compiler.

0

3 Answers 3

4

Initializers can only be used at declaration time. If you want to initialize b after declaration, then you can do it by using a compound literal-- a C99 feature:

b =  (struct udata){"ashok", 10, 'c'};  

GCC also support copound literals as an extension.

Sign up to request clarification or add additional context in comments.

Comments

3

What you're trying to do cannot be done directly in standard C. The best standard and portable solution is to use a temporary:

const struct udata tmp = {"ashok", 10, 'c'};
b = tmp;

However, in practice, the following is often (but not always!) allowed by compilers (*note below):

b = (struct udata){...};

(* note: I believe at least MSVC does not support this syntax, and probably many others; but just throwing it out there. GCC, however, does support it)

Comments

2

That's how C is designed and specified to work. There's nothing you can do. If you have a structure variable, you can only initialize it by an initializer in the declaration or by later initializing the individual members.


In the future, when posting a question regarding compiler errors, please include the complete and unedited error log in the question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.