+ 2
Why output is 16 instead of 15??
#include<stdio.h> main() { int a=6; int b=++a + ++a; printf("%d",b); }
14 Réponses
+ 8
the prefix (++a) operators takes precedence, so a is incremented twice, then the new value of a is added twice
to 8 + 8
+ 6
+ 2
int a = 6
b = ++a + ++a
b = 7+1 + ++a
b = 7+1 + 7+1
b = 8 + 8
b = 16
@sazzad
Your second example:
++a + ++a + ++a
From previous we know:
8 + 8 + ++a
= 16 + ++a
= 16 + 9
= 25
The a isn't always valued first in c++.
+ 2
The solution is in this line:
int b=++a + ++a;
First ++a makes “a” to 7 before the operand will be evaluated.
Second ++ grows “a” in the second operand to 8.
When the summation is runing, the “a” is 8.
8 + 8 is 16
------------------
In Java or PHP the operands evaluated before next operand, so there is the output is 15:
public class Program
{
public static void main(String[] args) {
int a=6;
int b=++a + ++a;
System.out.println( b );
}
}
----------
<?php
$a=6;
$b=++$a + ++$a;
printf("%d",$b);
?>
+ 1
Interesting. To be honest I can't explain how it works, but I think you already knew the answer.
The a is incremented twice before it calculate the b.
+ 1
I tried it in C# and it give me 15.
Tamás' explanation is right. Different language give different result.
0
Hi,
int b=++a + ++a;
a is increasing twice before the sum
demonstration:
b = a + a; =>b=12
b = ++a + a; =>b=14 because a=7 after increase
0
@Buray
According to your reply won't this code show 27???? why 24?
#include<stdio.h>
main()
{
int a=6;
int b=++a + ++a + ++a;
printf("%d",b);
}
0
@Tamas
According to your reply won't this code show 27???? why 24?
#include<stdio.h>
main()
{
int a=6;
int b=++a + ++a + ++a;
printf("%d",b);
}
0
@Faith
But,it is showing 24 in online compiler not 25
0
@Tamas
Why are you forcing to use parentheses in your own way??Why not ++a + (++a + ++a).My actual question is why it's showing 24??(You dictated that it shows 25.How??If you explain plz,I will be obliged a lot) 😊😊
0
for me the result must be 25 because operation is execute by even (pair)
b=++a + ++a + ++a; is like as b=(++a + ++a) + ++a;
so ++a + ++a = 16
b=16 + ++a = 16 + 9 = 25
0
@Tamaj @MBZH31
ok,I got 25!!!thanks
0
In your longer code…
int b=++a + ++a + ++a;
Use parentheses for understand…
int b=(++a + ++a) + ++a;
For second + operator the oprerands are “(++a + ++a)” and “++a”.
-------------------
Update:
The operations evaluated from left to right (except assignment).
The 24 is wrong, this code puts 25 in this way:
int b=++a + ++a + ++a;
1. first “++a” set “a” to 7
2. second “++a” set “a” to 8
3. first + operator works, so the second + operator gets the left operand as 16
4. third “++a” set “a” to 9
5. second + operator works, so 16 + 9 = 25