+ 9

#include<iostream> using namespace std; int main() { int a=10,b=20,sum=a+b; a=5; cout<<"The sum is\n"<< sum << endl;

here the variable value of ' a' doesn't change...it gives the output 30,why??

1st May 2017, 12:59 AM
MUʜAMMED ɪʟʟYAS
MUʜAMMED ɪʟʟYAS - avatar
8 Respostas
+ 14
The value of a does change. You just don't know it because you aren't outputting a. You are outputting sum, which is initialized as "a+b" before a is changed. So the initial value of a is used, and when a changes, it doesn't have any effect on the value of sum.
1st May 2017, 1:19 AM
J.G.
J.G. - avatar
+ 9
the output is 30 because 10+20 is 30
1st May 2017, 1:05 AM
chris
chris - avatar
+ 8
but i change the value of a???
1st May 2017, 1:06 AM
MUʜAMMED ɪʟʟYAS
MUʜAMMED ɪʟʟYAS - avatar
+ 6
haha I'll let you think about this one for a minute
1st May 2017, 1:08 AM
chris
chris - avatar
+ 5
the output is 30 because when sum was assigned the value of a+b value of a was 10.AFTER the statement sum=a+b you changed the value of a hence it won't affect 'sum'
1st May 2017, 6:56 AM
Harshitha P N
+ 2
In C++, variables on the left side of = are associated with memory locations. Once sum is computed, 30 is stored in the associated memory and nothing links it to the value of a anymore.
1st May 2017, 1:30 AM
Igor B
Igor B - avatar
+ 1
as I think you just want the out put sum and initially you gave the value of a as 10 and then you have asked for the sum of a and b so the compiler first completes this step and gives u the output as 30
2nd May 2017, 1:10 AM
M.varun M.varun
M.varun M.varun - avatar
+ 1
delete the a = 5 and everything is fine
24th May 2017, 6:42 PM
Kevin Frohn
Kevin Frohn - avatar