Sams Teach Yourself C in 21 Days

(singke) #1
The Pieces of a C Program: Statements, Expressions, and Operators 63

4


is an expression consisting of the sub-expressions 2 and 8 and the addition operator +.
The expression 2 + 8evaluates, as you should know, to 10. You can write C expressions
of great complexity:
1.25 / 8 + 5 * rate + rate * rate / cost
When an expression contains multiple operators, the evaluation of the expression
depends on operator precedence. The concept of operator precedence is covered later in
today, as are details about all of Cā€™s operators.
C expressions can get even more interesting. Look at the following assignment state-
ment:
x = a + 10;
This statement evaluates the expression a + 10and assigns the result to x. In addition,
the entire statement x = a + 10is itself an expression that evaluates to the value of the
variable on the left side of the equal sign. This is illustrated in Figure 4.1.

FIGURE4.1
An assignment state-
ment is itself an
expression.

Evaluates to a value

variable=any_expression;

Evaluates to the same value

Thus, you can write statements such as the following, which assigns the value of the
expressiona + 10to both variables,xandy:
y = x = a + 10;
You can also write statements such as this:
x = 6 + (y = 4 + 5);
The result of this statement is that yhas the value 9 andxhas the value 15. Note the
parentheses, which are required in order for the statement to compile. The use of paren-
theses is covered later today.

With just a few exceptions that will be noted throughout this book, assign-
Note ment statements should not be nested within other expressions.

07 448201x-CH04 8/13/02 11:15 AM Page 63

Free download pdf