Help - Output related confusion

void main()
{
int b=-1;
-b;
cout<<b;
getch();
}
Output is -1 .

Why isnt this output 1 .. Why d 3rd line -b not working .. It shud hv been -(-1) dats is 1 isnt ??

Comments

  • Hello, the problem is that statement "-b;" does nothing, it is not caught by the compiler because it is a calculation. That means that you will not get an error message for it. You need to make sure to reassign the variable. Here is a couple of ways of doing this

    b = -b; this just reassigns b to the negative value of itself.

    or:

    b *= -1; this would multiply b by negative one, which changes the sign
    and then assigns it back to the b variable.

  • [color=Blue]Good compiler will say: "Code has no effect." on this line.[/color]
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories