Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "i" variable getting incremented twice in my program?

Tags:

c

macros

One of my friend showed me this program and asked me why is i variable getting incremented twice.

According to my understanding MAX(i++, ++j); in this line i is first send as a parameter and then incremented, so if the initial value of i is 10 then the incremented value should be 11, but it shows the incremented value of i as 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 me how is the value incremented to 12 ?

Thanks.

like image 566
Searock Avatar asked Feb 03 '11 10:02

Searock


People also ask

What does increment a variable mean?

To increment a variable means to increase it by the same amount at each change. For example, your coder may increment a scoring variable by +2 each time a basketball goal is made. Decreasing a variable in this way is known as decrementing the variable value.

How to increment a variable by 2?

You can also write like this test += 1; it means test = test+1; For incrementing the value of test by 2,3 or by any number you just need to write how much times you want to increment it . For 2 you should write test+=2.

How to increment number in PHP?

C style increment and decrement operators represented by ++ and -- respectively are defined in PHP also. As the name suggests, ++ the increment operator increments value of operand variable by 1. The Decrement operator -- decrements the value by 1. Both are unary operators as they need only one operand.


1 Answers

MAX is a macro, not a function. In your use case, it expands to:

k = (i++) > (++j) ? (i++) : (++j);
like image 50
Oliver Charlesworth Avatar answered Oct 26 '22 15:10

Oliver Charlesworth