Statements

We saw in the early examples that the actions in C programs are defined in statements. Here we consider the commonest sorts of statements and ways of grouping them to achieve the effects we desire in our programs.

As well as linking these sections to allow you to work through them in order, there is a direct route to any particular type of statement you want to learn about through the index below.

Expressions and statements

It is important to note that in C and C++ it is legitimate to use an expression as a statement. At first sight this might seem strange, since there is no visible effect in writing a simple arithmetic expression, such as 3 + 5. It is important to realise, however, that an expression may involve a side effect. This is usually where a function call is made in the expression. The function may cause various actions to happen, such as reading in an item or assigning to a location, even thought these are not visible in the expression where the call is made.

The other effect of blurring the distinction between expressions and statements is that an assignment can be viewed as an expression. This means that the following is a valid expression:

5 + (y=3)
with the value 5+3. The value of an assignment used as an expression is the value of its right hand side.

Note also that two common C programming mistakes result from this blurring.

Missing function parentheses
Where a function is called without arguments it is necessary to write empty parentheses. Failing to write them means that the statement becomes an expression, with its value equal to a pointer to the function. This means nothing happens when the "call" is reached.

Assignment instead of comparison
When you write the equality comparison operator, be careful not to accidentally write the assignment operator (single equals sign instead of double). If the result is a valid assignment of integral type you will end up with a totally unexpected effect.


Exercises on this section.


Next.


Assignment
Conditional statements
An example program using conditionals
Compound statement
While loop
For loops
An example of a for loop
Further example of loops
switch statements

Back to Main Contents page.