Slycoder
Slycoder

Reputation: 1

Reading strings without function

>char str[20]="HELLO"; 

is correct, while

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

isn't. WHY?

Upvotes: 0

Views: 25

Answers (1)

Armali
Armali

Reputation: 19375

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.

Upvotes: 2

Related Questions