Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluation and Truncation

Tags:

c

truncation

What occurs first, truncation or evaluation? If I do this:

int a = (2+3)*10.5;

a gets 52, but if I do this:

int a = 30 / 4 * 5; 

a gets 35.

So an expression is evaluated first and then truncated. Then the truncated value is used for other calculations? 'Cause in the second statement "30/4" is evaluated first and then it gets truncated to 7. What are the exact rules for this? Anything from the documentation... I'm not talking about type conversion, just truncation in this case, like expressions get truncated one after the other?

like image 751
duckkkk Avatar asked Feb 11 '26 08:02

duckkkk


1 Answers

You're kind of asking the wrong question, there's no such thing as separate evaluation and truncation steps. Truncation is a side effect of a type conversion, if the converted value can't be represented exactly in the target type, like

double d = 2.5;
int i = d;       // 2.5 is truncated as a side effect of converting to int

So what you have to know is how operands are converted when evaluating an expression. The exact rules are a bit complicated, I'll focus on the basics here. In general, with arithmetic operators, if the operands don't have the same type already, one of them is converted in a way so both values can be represented. In your first example:

int a = (2+3)*10.5;

2 and 3 are both of type int, so they're just added -- the result (5) has type int again.

But 10.5 has type double. So, 5 is converted to double as well, the result is 52.5. Only because you assign that to an int, it gets converted back to int and therefore, truncation must take place.

In your second example:

int a = 30 / 4 * 5;

Both 30 and 4 have the type int. Therefore, no conversion takes place and the division is carried out directly.

Here's the catch: dividing two integers is an integer division which again results in an int (here: 7). That's not truncation, it's just how integer divisions are defined. In fact, you probably learned about that operation early in school, using an algorithm called long division with remainder. There's an "opposite" operation modulo (%) in C which would give you the remainder of that division.

So, here you have the result 7 of type int, which is then multiplied by 5, another int, therefore, again, no conversion -- the final result is 35.

Check what happens if you write

int a = 30.0 / 4 * 5;

instead. Now, the first operand of / is a double, so 4 is converted to double as well and the result is 7.5 -- which is again a double, causing the 5 to be converted to a double and yielding the final result of 37.5.

This is again converted to int because you assign it to an int and truncation yields 37.


Note how the operator / means two different things here (real division vs integer division), depending on the type of its operands.