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.
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.
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.
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.
MAX
is a macro, not a function. In your use case, it expands to:
k = (i++) > (++j) ? (i++) : (++j);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With