0
>char str[20]="HELLO"; 

is correct, while

>char str[20];
>
str="HELLO"; 

isn't. WHY?

1 Answer 1

2
char str[20]="HELLO";

The above is a declaration and also a definition of the identifier str, and has an initializer, "HELLO". The C standard says about this initialization:

An initializer specifies the initial value stored in an object.

An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

char str[20];
str="HELLO";

The first line here is again a declaration and also a definition of the identifier str, but without an initializer. The second line is a statement with an assignment expression. The constraint for an assignment is:

An assignment operator shall have a modifiable lvalue as its left operand.

Regarding lvalues, arrays, …:

A modifiable lvalue is an lvalue that does not have array type, …

So, trying to assign to an array is a constraint violation.

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

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.