Search code examples
c++expressioncomputer-sciencedeclarationdefinition

I want to understand in detail distinct between expression and statement in C++. Pls pick concrete example to explain that


Now I am learning C++ programming. I didn't understand the distinction between expression, definition, declaration, and definition.

As Wikipedia says,

In "Statement(computer science)"

In most languages, statements contrast with expressions in that statements do not return results and are executed solely for their side effects, while expressions always return a result and often do not have side effects at all.

In "Expression(Computer Science)" page

In many programming languages a function, and hence an expression containing a function, may have side effects. An expression with side effects does not normally have the property of referential transparency. In many languages (e.g. C++), expressions may be ended with a semicolon (;) to turn the expression into an expression statement. This asks the implementation to evaluate the expression for its side-effects only and to disregard the result of the expression (e.g. "x+1;") unless it is a part of an expression statement that induces side-effects (e.g. "y=x+1;" or "func1(func2());"). Caveats

Concretely, What do "side effects" and "result" mean here?

Help me, C++ Geeks!


Solution

  • Concretely, What do "side effect" and "result" mean here?

    Expression has no side-effects, when removing it from source does not change program semantics.

    int main(void) {
       int x = 1, y = 2, z = 0;
       // x+y expression calculates sum and ignores resulting answer 
       // NO SIDE EFFECTS, can be removed
       x+y; 
       // x+y expression calculates sum, but then 15 is assigned to z as a result 
       // SIDE EFFECT is that removing given expression breaks program syntax - can't be removed 
       z = (x+y, 15);
    }
    

    EDIT

    BTW, keep in mind that not all expression statements has side-effects too. For example x=x; is technically equivalent to ; - an empty statement which is compiled into NOP at assembly level or skipped by GCC optimizer at all. So these kinds of expression statements has no side-effects and can be removed safely from a program. But it doesn't mean that you can remove each empty statement without changing program logic. For example as in this snippet :
    for (i=0; i < 10; i++);
    Here NOP is executed with each CPU cycle, so if you will remove it - program semantics will change radically.