3 Everything is about control
This chapter covers
- Conditional execution with
if
- Iterating over domains
- Making multiple selections
In our introductory example, listing 1.1, we saw two different constructs that allowed us to control the flow of a program’s execution: functions and the for
iteration. Functions are a way to transfer control unconditionally. The call transfers control unconditionally to the function, and a return
statement unconditionally transfers it back to the caller. We will come back to functions in chapter 7.
The for
statement is different in that it has a controlling condition (i < 5
in the example) that regulates if/when the secondary block ({
printf
(...) }
) is executed. C has five conditional control statements: if
, for
, do
, while
, and switch
. We will look at these statements in this section: if
introduces a conditional execution depending on a Boolean expression; for
, do
, and while
are different forms of iterations; and switch
is a multiple selection based on an integer value.
C has some other conditionals that we will discuss later: the ternary operatorC, denoted by an expression in the form cond ? A : B
(section 4.5); the compile-time preprocessor conditionals #if
, #ifdef
, #ifndef
, #elif
, #elifdef
, #elifndef
, #else
, #endif
(section 8.1.5); and type-generic expressions denoted with the keyword _Generic
(chapter 18).
3.1 Conditional execution
The first construct that we will look at is specified by the keyword if
. It looks like this: