Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
// total and sum3 values must be same after execution of the below two c codes
void main()
{
int a=10;
int total;
printf("Value of a before ++a is :%d\n",a);
++a;
printf("Value of a after ++a is :%d\n",a);
total=(((++a)*(10))+((++a)*(10))+((++a)*(10)));/* total and sum3 values must be same after execution of the below two c codes*/
printf("Value of total is :%d\n",total );


int a=10;
int sum1,sum2,sum3;
printf("Value of a before ++a is :%d\n",a);
++a;
printf("Value of a after ++a is :%d\n",a);
sum1=((++a)*10); // here total is broken into sum1, sum2, sum3
sum2=(sum1)+((++a)*10);
sum3=(sum2)+((++a)*10);
printf("Value of sum1 is :%d\n",sum1 );
printf("Value of sum2 is :%d\n",sum2 );
printf("Value of sum3 is :%d\n",sum3 );
printf("Value of ++a at end is :%d\n",a);
}
Posted

1 solution

im getting total=400 and sum3=390. But total has to be 390. Please suggest.
 
Share this answer
 
Comments
Richard MacCutchan 2-Jun-15 11:58am    
That is because you are using the expression ++a multiple times in a single statement. In such cases the results are not guaranteed because the compiler may well evaluate that once and then use it in every calculation. This is a known limitation of C++ compilers.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900