Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the return statement considered to be an expression statement in C?

Tags:

c

expression

I heard that if an expression is followed by a semicolon, then it is considered to be an expression statement.

Source: http://farside.ph.utexas.edu/teaching/329/lectures/node11.html

int x = 7;
x = 8;
x++;
x—-;
x = x << 1;

These are all expression statements.

But is this an expression statement too?

return 5;

And if not, then please throughly explain why.

And I would also appreciate it if you could tell whether the return satetement can be considered an expression statement in other languages as well.

like image 887
Patrik Nusszer Avatar asked Dec 14 '22 11:12

Patrik Nusszer


2 Answers

A return statement and an expression statement are two different things.

Section 6.8.3 of the C standard gives the syntax for an expression statement:

expression-statement:

  • expressionopt;

While section 6.8.6 gives the syntax of a return statement:

jump-statement:

  • goto identifier;
  • continue;
  • break;
  • return expressionopt;

Also, this is not an expression statement (in fact not a statement at all):

int x = 7;

But a declaration.

like image 162
dbush Avatar answered Jan 17 '23 13:01

dbush


This is basically answered by Expression Versus Statement. The key question is: Does a return evaluate to a value (e.g. could you do x = return 5;?). Clearly it does not, so it is a statement, not an expression. Expression statements are just expressions used as statements; if it's not an expression, it can't be an expression statement, so return does not form an expression statement.

like image 43
ShadowRanger Avatar answered Jan 17 '23 14:01

ShadowRanger