Search code examples
operatorsturbo-c++turbo-cassociativity

weird operator precedence and assignment behavior in borland turboC++


I have to use borland TurboC++ for C programming in my college. They say our examination board recommends it. I have to use it..

The problem is that they gave this operator precedence related question:

int a=10,b=20,result;
result1 = ++a + b-- - a++ * b++ + a * ++b;
printf("result=%d",);
printf("\n a=%d",a);
printf("\n b=%d",b);

Other compilers like gcc can't perform this operation. But turbo C can and gives us:

result=32 a=12 b=21

I made mistake in my test. My teacher tried to explain what's going on. But I am not convinced. Is it some kind of weird behavior of turbo C or in older days it used to be totally fine with all compilers. If so, what are the steps to understand what is going on and how to understand.


Solution

  • To solve these kind of problem, turbo-c do it in manner as follows :

    1) Consider the initial value of variables used.

    a=10
    b=20
    

    2) Count all the pre-increment and decrements for each variable and store all post on stack separate for each variable.

    for variable a

    pre increment = 1 therefore change the value of a to 11
    post = 1 stored to stack
    

    for variable b

    pre increment = 1 therefore change the value of b to 21
    post = 2 stored to stack
    

    3) Now replace all the pre and post with the current value of a and b

    result = 11 + 21 - 11 * 21 + 11 * 21 ;
    result = 11 + 21;
    result = 32;
    

    4) lastly pop the stack and perform the operation on the variable.

    a = 12
    b = 21
    

    This the only way to solve this problem. You can check the procedure with any question of same kind. The result will came out same. g++ fails to solve because it probably cannot resolve the variable in the same way thus the precedence error came in picture. It might probably fail with ++ + and -- - because it cannot understand the increment or decrements operator and forms ambiguous trees.