-1
#include <stdio.h>
#include <stdlib.h>

int main()
{
  int a , b ,c ;
  printf("Enter values for a and b: ");
  scanf("%d%d",&a,&b);

    a = a + b-- ;

  if (a<b){
    c = -1;
  printf("\n\t%d %d %d\n\n",a,b,c);
          }
  else {
    c = 0;
    printf("\n\t%d %d %d\n\n",a,b,c);
       }
}

Lets assume the value of the input for a and b are 2 (for both of them).
I studied the above program, but when it comes to the output it will be 4 1 0, a=4,b=1,c=0. But, the calculation part above said that a=a+b-1 which will be the value of a is 3, now the new value of a is 3. But for b the value is still 2 because we didn't assign a new value to it.

I am very confused about the output.

Hamoud
  • 23
  • 5

2 Answers2

2

There is a difference between a+1, a++ and ++a. Details here. Therefore, when you say

a = a + b--;

You are actually saying

a = a + b;
b = b - 1;

If you say

a = a + --b;

It becomes

b = b - 1;
a = a + b;

And if you say

a = a + (b-1)

It does what you think: a = a + b - 1. The value of b doesn't change afterwards.

Henry Fung
  • 380
  • 3
  • 12
1

At the beginning, a and b are both 2

Then, you execute a = a + b--;.

The decrement operator is located after the b, so it evaluates to:

a=a+b;
b=b-1;

After this, a will be 4 and b will be 1.

a is not smaller than b, so c will be 0.

Note:

If it would be a = a + --b, it would evaluate to

b=b-1;
a=a+b;

Because the -- is executed at the beginning of the evaluation.

dan1st
  • 12,568
  • 8
  • 34
  • 67