470,810 Members | 1,033 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,810 developers. It's quick & easy.

Unexpected output of Program

Expand|Select|Wrap|Line Numbers
  1. int a=5;
  2. int b=a++ + ++a + a++;
  3. printf("%d",b);
the output for this code is 19

Expand|Select|Wrap|Line Numbers
  1. int a=5,b;
  2. b=a++ + ++a + a++;
  3. printf("%d",b);
but the output for this code is 18.

Jul 31 '11 #1
3 2353
9,208 Expert Mod 8TB
The C language standard provides no rules for when a compiler can change variable values inside a single statement. As a result, if you change the value of a variable more than once in a single statement, the compiler can make the changes in any order it chooses.

This is termed indeterminate results.
Jul 31 '11 #2
83 64KB

In my system both program give same answer 19,so may be it is depend on compiler.You use a for multiple time so,it is depend on compiler.There is no specific rules for compiler.
Apr 30 '20 #3
I recommend this method over a for (t = 0; t < b; t++). Imagine if you were using 64-bit math, the for loop would take a long time, even on a computer. OP doubling method of a=a+a was on track, but incomplete.

unsigned a;
unsigned b;
unsigned product = 0;
scanf("%u%u", &a, &b);
while (b > 0) {
if (b & 1) {
unsigned OldProduct = product;
product += a;
if (product < OldProduct) {
b >>= 1; // Halve b
a += a; // Double a - avoid using multiplication
printf("\nProduct = %u\n", product);
Apr 30 '20 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

reply views Thread by Steve Holden | last post: by
3 posts views Thread by Mahmood Ahmad | last post: by
2 posts views Thread by Zach Flynn | last post: by
1 post views Thread by kurt.krueckeberg | last post: by
2 posts views Thread by Evan Carmi | last post: by
17 posts views Thread by Hypnotik | last post: by
reply views Thread by mihailmihai484 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.