Arithmetic Ordering in C Programming Language

Whilst we are dealing with arithmetic we want to remind you about something that everyone learns at junior school but then we forget it. Consider the following calculation:

a=10.0 + 2.0 * 5.0 - 6.0 / 2.0

What is the answer? If you think its 27 go to the bottom of the class! Perhaps you got that answer by following each instruction as if it was being typed into a calculator. A computer doesn't work like that and it has its own set of rules when performing an arithmetic calculation.  In the above calculation the multiplication and division parts will be evaluated first and then the addition and subtraction parts. This gives an answer of 17.

Note: To avoid confusion use brackets. The following are two different calculations:

a=10.0 + (2.0 * 5.0) - (6.0 / 2.0)

a=(10.0 + 2.0) * (5.0 - 6.0) / 2.0

You can freely mix intfloat and double variables in expressions. In nearly all cases the lower precision values are converted to the highest precision values used in the expression. For example, the expression f*i, where f is afloat and i is an int, is evaluated by converting the int to a float and then multiplying. The final result is, of course, a float but this may be assigned to another data type and the conversion will be made automatically. If you assign to a lower precision type then the value is truncated and not rounded. In other words, in nearly all cases you can ignore the problems of converting between types.
This is very reasonable but more surprising is the fact that the data type char can also be freely mixed with ints,floats and doubles. This will shock any programmer who has used another language, as it's another example of C getting us closer than is customary to the way the machine works. A character is represented as an ASCII or some other code in the range O to 255, and if you want you can use this integer code value in arithmetic. Another way of thinking about this is that a char variable is just a single-byte integer variable that can hold a number in the range O to 255, which can optionally be interpreted as a character. Notice, however, that C gives you access to memory in the smallest chunks your machine works with, i.e. one byte at a time, with no overheads.


Learn More :