Hi
Could you please tell me how to solve this simple problem in c++.

#include<iostream.h>
#include<conio.h>

void main()

{

    clrscr();
    int a=5,b=3;
    int y=a-b++ * --b; /* manually I get the answer as 6 , but the compiler gives as -4 . how?*/
    cout<<y;
    getch();
}

Can you explain more about line 6 algorithm? Why are you incrementing and decrementing b?

In order to get the answer as 6 remove increment and decrement operators and use brackets.

Hope that helps.

manually I get the answer as 6 , but the compiler gives as -4 . how?

Because modifying a variable multiple times between sequence points is undefined behavior. The compiler can do whatever it wants. Further, upon invoking undefined behavior, the entirely of the program is henceforth undefined as well. So even if you get the result you want, that doesn't guarantee something else unrelated won't produce unpredictable results.

The fix is to move the expressions with side effects such that you get the result you actually want.

That is the power of precedence.
The multiplication will take the power. thats int y =a-b++ * --b;
you need to put them in a correct arragement depending on what you want to achieve such as.
1. int y = (a - b++)*--b;
2. int y = a-(b++ * --b);

Any selection above will at least provide you with a constant answer because the compiler will explicitly understand your intention.

int y = (a - b++)*--b;
int y = a-(b++ * --b);

Both of these still invoke undefined behavior. Parentheses won't save you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.