Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explaining the difference between a statement and an expression in c++

Tags:

c++

expression

I am trying to understand thoroughly the difference between a statement and an expression
But i am finding it confusing even after reading this answer Expression Versus Statement
look at the following:

std::cout << "Hello there? " ;  

I could say that it is a statement as it is ending with a semi- colon BUT i could also say
It is an expression since i have an ostream , an output operator and a string literal
and this expression yields a value which is the left hand operand.
Which one is correct?

like image 859
Samuel Avatar asked Dec 22 '14 09:12

Samuel


1 Answers

Let's see what the C++ grammar can tell us:

statement:
  labeled-statement
  attribute-specifier-seq_opt expression-statement
  attribute-specifier-seq_opt compount-statement
  attribute-specifier-seq_opt selection-statement
  attribute-specifier-seq_opt iteration-statement
  attribute-specifier-seq_opt jump-statement
  declaration-statement
  attribute-specifier-seq_opt try-block

expression-statement:
  expression_opt ';'

So it is a statement; in particular, an "expression statement", which consists of a (potentially empty) expression followed by a semi-colon. In other words,

std::cout << "Hello there? "

is an expression, while

std::cout << "Hello there? " ;

is a statement.

like image 68
Angew is no longer proud of SO Avatar answered Nov 16 '22 01:11

Angew is no longer proud of SO