Is variable assignment a statement or expression?

Viewed 3207
2 Answers

Well, when you say

int x = 5;

that's a declaration, that happens to include an initialization.

But if you say

x = 5

that's an expression. And if you put a semicolon after it:

x = 5;

now it's a statement.

Expression statements are probably the most common type of statement in C programs. An expression statement is simply any expression, with a semicolon after it. So there are plenty of things that might look like some other kind of statement, that are really just expression statements. Perhaps the best example is the classic

printf("Hello, world!\n");

Many people probably think of this as a "print statement". But it's actually just another expression statement: a simple expression consisting of a single function call

printf("Hello, world!\n")

again followed by a semicolon.

Roughly speaking, in C;

  • A statement is a section of code that produces an observable effect;
  • An expression is a code construct which accesses at least one data item, performs some operation of the result of that access (or those accesses), and produces at least one result. An expression may be composed of (smaller) expressions.

An expression statement is a statement that has the single purpose of evaluating an expression - although that expression may be arbitrarily complex (including composed from other expressions). There are other types of statements such as jump statements (e.g. goto), label statements (e.g. the target of a goto), selection statements which make decisions (e.g an switch, if), and iteration statements (e.g. loops), etc

A declaration like;

 int x = 5;

defines the variable named x and initialises it with the expression 5. 5 is a literal value.

If x has been previously declared,

 x = 5;

is a simple expression statement - its sole purpose is evaluating an assignment expression. The 5, again, is a literal with value 5. x = 5 is therefore an expression, which assigns x to have the value 5. The result is the value 5, which is why the expression statement

 printf("%d\n", (x = 5));

both assigns x to have the value 5 and prints the value 5

Related