|
Page 2 of 3 Increment and Decrement C has two special, dedicated, operators which add one to and subtract one from a variable. How is it a minimal language like C would bother with these operators? They map directly into assembler. All machines support some form of “inc” instruction which increments a location in memory by one. Similarly all machines support some form of “dec” instruction which decrements a location in m Prefix and Postfix The two versions of the ++ and -- operators, the prefix and postfix versions, are different. Both will add one or subtract one regardless of how they are used, the difference is in the assigned value. Prefix ++, -- When the prefix operators are used, the increment or decrement happens first, the changed value is then assigned. Thus with: i = ++j; The current value of “j”, i.e. 5 is changed and becomes 6. The 6 is copied across the “=” into the variable “i”. Postfix ++, -- With the postfix operators, the increment or decrement happens second. The unchanged value is assigned, then the value changed. Thus with: i = j++; The current value of “j”, i.e. 5 is copied across the “=” into “i”. Then the value of “j” is incremented becoming 6. What is actually happening here is that C is either using, or not using, a Registers temporary register to save the value. In the prefix case, “i = ++j”, the increment is done and the value transferred. In the postfix case, “i = j++”, C loads the current value (here “5”) into a handy register. The increment takes place (yielding 6), then C takes the value stored in the register, 5, and copies that into “i”. Thus the increment does take place before the assignment. Truth in C § To understand C’s comparison operators (less than, greater than, etc.) and the logical operators (and, or, not) it is important to understand how C regards truth. § There is no boolean data type in C, integers are used instead § The value of 0 (or 0.0) is false § Any other value, 1, -1, 0.3, -20.8, is true if(32) printf("this will always be printed "); if(0) printf("this will never be print"); Truth in C C has a very straightforward approach to what is true and what is false.Any non zero value is true. Thus, 1 and -5 are both true, because both are non True zero. Similarly 0.01 is true because it, too, is non zero. Any zero value is false. Thus 0, +0, -0, 0.0 and 0.00 are all false. Thus you can imagine that testing for truth is a very straightforward operation in Testing Truth C. Load the value to be tested into a register and see if any of its bits are set. If even a single bit is set, the value is immediately identified as true. If no bit is set anywhere, the value is identified as false. The example above does cheat a little by introducing the if statement before we have seen it formally. However, you can see how simple the construct is: if(condition) statement-to-be-executed-if-condition-was-true ;
|