hassan236 wrote: |
---|
What is the difference between statements and expressions? |
The most important difference is that an expression has a type and will give you a value of that type unless the type is void. A statement does not have a type and does not result in a value.
Examples of expressions:
Any expression can be turned into a statement by putting a semicolon after it.
This is an expression:
This is a statement (that contains an expression):
There are also other kind of statements, some of which does not end in a semicolon.
If statements:
1 2 3 4
|
if (cond)
{
doSomething();
}
| |
Loop statements:
1 2 3 4
|
while (x < 100)
{
std::cout << ++x << "\n";
}
| |
Variable declaration statements:
Note that some of these statements contain other statements and/or expressions.
In some places you are expected to use statements and in other places you are expected to use expressions.
The body of a function contains a list of
statements. If you instead write a list of expressions (without semicolons) you would get a compilation error.
1 2 3 4 5 6
|
void bar()
{
5+9
std::gcd(1, 100) // ERROR!
foo()
}
| |
The arguments that you pass to functions should be
expressions. You cannot write statements instead. That won't work.
1 2
|
// This is an error no matter how someFunction is defined:
someFunction(foo();, if(cond){doSomething();});
| |