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
Which one is correct?
Both: it is an expression statement. C and C++ let you put an expression into a body of code, add a semicolon, and make it a statement.
Here are some more examples:
x++; // post-increment produces a value which you could use
a = 5; // Assignment produces a value
max(a, b); // Call of a non-void function is an expression
2 + x; // This calculation has no side effects, but it is allowed
Note that this is true in the specific case of C and C++, but may not be true in case of other languages. For example, the last expression statement from the list above would be considered invalid in Java or C#.
The definition of expression is given in the C Standard (6.5 Expressions)
1 An expression is a sequence of operators and operands that specifies computation of a value, or that designates an object or a function, or that generates side effects, or that performs a combination thereof. The value computations of the operands of an operator are sequenced before the value computation of the result of the operator.
As for expression-statements then they are ended with a semicolon. Here is the definition of the expression statement in C++
expression-statement:
expression opt;
And
An expression statement with the expression missing is called a null statement.
Relative to the last quote I would like to point to a difference between C and C++. In C++ declarations are statements while in C declarations are not statements. So in C++ you may place a label before a declaration while in C you may not do so. So in C you have to place a null statement before a declaration. Compare
C++
Label:
int x;
C
Label: ;
int x;
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.