Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating Expressions and Statements 69

4


Although every statement in the block must end with a semicolon, the block itself does
not end with a semicolon, as shown in the following example:
{
temp = a;
a = b;
b = temp;
}
This block of code acts as one statement and swaps the values in the variables aand b.

DOend your statements with a semi-
colon.
DOuse whitespace judiciously to make
your code clearer.

DON’Tforget to use a closing brace any
time you have an opening brace.

DO DON’T


Expressions ............................................................................................................


Anything that evaluates to a value is an expression in C++. An expression is said to
returna value. Thus, the statement 3+2;returns the value 5 , so it is an expression. All
expressions are statements.
The myriad pieces of code that qualify as expressions might surprise you. Here are three
examples:
3.2 // returns the value 3.2
PI // float constant that returns the value 3.14
SecondsPerMinute // int constant that returns 60
Assuming that PIis a constant created that is initialized to 3.14 and SecondsPerMinute
is a constant equal to 60, all three of these statements are expressions.
The slightly more complicated expression
x = a + b;
not only adds aand band assigns the result to x, but returns the value of that assignment
(the value of x) as well. Thus, this assignment statement is also an expression.
As a note, any expression can be used on the right side of an assignment operator. This
includes the assignment statement just shown. The following is perfectly legal in C++:
y = x = a + b;
Free download pdf