Definitions.
20*30
)
is how you tell the computer to perform arithmetic
(and/or other more exotic operations).
*
)
for multiplication.
20*30
is
600
.
20*30
has a value, it can be used as part of a larger expression such as
10+20*30
.
610
is of type
int
,
and the value
'A'
is of type
char
.
+
-
*
/
etc.
x
for multiplication?
10
20
3.14
i
j
k
price
10+20
price+20
i-j+10
-a
+a
a+b
a-b
b=a
cout<<a
cin>>a
a?b:c
places.C
:
three places where we can write an expression in a C++ program.
int i {10 + 20}; //i is born holding 30or out of variables that are currently holding a value:
int j {10}; //j is born holding 10 int k {j + 20}; //k is born holding 30Don’t do this:
int j; //j is born containing unpredictable garbage int k {j + 20}; //k is born containing bigger unpredictable garbageAnd the following snippet will be totally rejected by our C++ compiler
c++
.
The program won’t even “compile”.
int k {j + 20}; //The computer doesn't know yet what "j" means. int j {10};
precedence.C
:
*
(multiplication, line 5)
has higher precedence then
+
(addition, line 6).
-
(negative, line 3)
has higher precedence then
-
(subtraction, line 6).
-
(negative, line 3) is a unary operator,
while
-
(minus, line 6) is a binary operator.
That’s how you tell them apart.
associativity.C
:
addition and subtraction have left-to-right associativity.
lobster.C
.
Example of an expression.
Then you bank the heat and let the kettle simmer—ten minutes for the first pound of lobster, then three minutes for each pound after that. (This is assuming you’ve got hard shell lobsters, which, again, if you don’t live between Boston and Halifax is probably what you’ve got. For shedders [soft-shell], you’re supposed to subtract three minutes from the total.) |
||
—David Foster Wallace, Consider the Lobster |