Why does the variable "i" get an increase in my program twice?

One of my friends showed me this program and asked me why the variable igets doubled.

According to my understanding MAX(i++, ++j);, this line is ifirst sent as a parameter and then increased, therefore, if the initial value iis equal 10, then the increment of the value should be 11, but it shows the increased value ias 12.

Program:

#include<stdio.h>

#define MAX(x,y) (x)>(y)?(x):(y)

void main(void)
{
    int i = 10;
    int j = 5;
    int k = 0;

    k = MAX(i++, ++j);

    printf("%d %d %d",i,j,k);
}

Output:

12 6 11

Can someone please explain to me how the value increases to 12?

Thank.

+5
source share
8 answers

, (i++)>(++j)?(i++):(++j).

+5

MAX - , . :

k = (i++) > (++j) ? (i++) : (++j);
+8

#define MAX(x,y) (x)>(y)?(x):(y)

 k = MAX(i++, ++j);

k = (i++)>(++j)?(i++):(j++);

, , .

+5

MAX . i .

MAX - . , :

k = (i++)>(j++)?(i++):(j++)

, .

+4

, k = MAX(i++, ++j); :

k = (i++)>(++j)?(i++):(++j);
+2

Macro MAXexpands to

(i++)>(++j)?(i++):(++j)

shows why you get double growth.

+2
source

The macro will expand to something like C pseudo-code:

if( i++ > j++)  // i is incremented the first time,  j is incremented once
   return i++;  // i is incremented the second time
else
   return j++;  // we never go there, so j is not incremented twice
+2
source

When used, the MAX(i++, ++j)generated code will be:

(i++) > (++j) ? (i++) : (++j)

Using a preprocessor macro simply extends the code and copies / pastes the arguments. You can use the function for this case.

int max(int x, int y)
{
  return (x > y ? x : y);
}

The modern compiler will enable it, observing the original behavior of the function call.

+1
source

All Articles