Statement Intro
Any legal expression can be a statement. For example:
;
3;
7 + sqrt(121);
The first is an empty statement, the second is a simple expression statement. The third is an expression containing a function.
A block statement is a sequence of zero or more statements enclosed between curly braces:
{
int x = 3;
cout << x << endl;
{
int x = 5;
cout << x << endl;
}
cout << x << endl;
}
The block statement above contains four statements, the third of which
is another block statement. Notice that:
int x = 3;
defines a variable which is local to the block where it is defined.
Also, the definition of a variable bearing the same name within an inner block,
as in:
int x = 5;
makes this second variable available only in the inner block,
while the other
x variable is inaccessible
in such a block.
Example
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
; // any legal expression can be a statement
3;
7 + sqrt(121); // ok, most compilers give you a warning
// block statement
{
int x = 3; // this variable is local to this (outer) block
cout << x << endl;
{
int x = 5; // this variable is local to this (inner) block. The is no way to access the outer x from here
cout << x << endl;
}
cout << x << endl;
}
}
Output
3
5
3