Getting Started

(lily) #1

Chapter 4: C Types, Operators, and Expressions


So the rong, according to C it is –25. The compiler does the


urus will memorize the precedence and associatively table and actually

served insult. Don’t be
lever be clear. Clever programming is difficult to read and understand. If the
clever programmer gets run over by a truck (hopefully) his code will be inherited
by some poor guy who will have to figure things out. DO NOT


answer is 40, right? W
division and multiplication first, then the addition and subtraction:


x = 50 + 10 / 2 – 20 * 4
x = 50 + 10 / 2 – 80
x = 50 + 5 – 80
x = 55 – 80
x = -25

Some C g
write statements like x = 50 + 10 / 2 – 20 * 4. Such clever programmers are
dangerous and should be avoided when possible. The Germans have a word for
clever: kluge, and in programming ‘kluge’ is a well-de
c


memorize the
Table of Operator Precedence and Associatively in C. DO use ’(‘ and ‘)’ to
make your program clear!


Which is clearer:
x = 50 + 10 / 2 – 20 4;
or:
x = 50 + (10 / 2) – (20
4);


The second adds nothing for the compiler, but tells the reader what was intended.
But what if you really meant to have the operations performed in the order listed?
Then you would write:
x = ((((50 + 10) / 2) – 20) * 4);


Which would make x = 40. The parentheses can get mighty confusing, but not
nearly as confusing as their absence.


Table 7: Operator Precedence and Associativity in C


Operator Type Operators Associativity
Expression () []. -> Left to right
Unary - + ~! & ++ -- sizeof(type) Right to left
Multiplicative
/ % Left to right
Additive + - Left to right

Free download pdf