Click here to Skip to main content
15,887,822 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I'm a Computer Science student in Master of Science degree. I'm teaching c language to undergraduate students.
Consider this program :

XML
#include <stdio.h>
#include <conio.h>

int main() {

    clrscr();

    float f=4;
    float g = f / 4 + f * 2 / ++f;
    printf("%5.2f", g);
    getch();
}


To my knowledge expression evaluation is done from left to right and based on operators precedence.
Here precedence of ++ is higher than + - / * operators. And, precedence of * / is higher than + - operators. So, the expression must be computed as:
g = f / 4 + f * 2 / ++f;
g = (f / 4) + ((f * 2) / ++f);
........1....5......2....4...3....
and the result must be:
g = 2.6

but, the compiler computes the expression as:
g = (f / 4) + ((f * 2) / ++f);
........4....5......1....3...2....
and the result is:
g = 2.85

Why this happens with no paranthesis in expression ?
I tested this issue in Turbo C and Borland C compilers.

Special Thanks
Posted
Updated 29-Nov-10 23:25pm
v2

1 solution

It happens because of operator precedence - google will help you with that - so it does make some sense.

I wouldn't do that - it isn't obvious what you actually want to happen, and that makes it difficult for a mere mortal to comprehend at a glance - the way most people read code. Re work it to two lines: It both makes it clearer for us, but also for the compiler:
C#
float g = f / 4 + f * 2 / (f + 1);
f++;
I would also tend to add more brackets to make it absolutely obvious - but then, I've translated code between languages before...
C#
float g = (f / 4) + ((f * 2) / (f + 1));
f++;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900