Unexpected output of Program

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ayan Dasgupta
    New Member
    • Mar 2011
    • 5

    Unexpected output of Program

    Code:
    int a=5;
    int b=a++ + ++a + a++;
    printf("%d",b);
    the output for this code is 19

    Code:
    int a=5,b;
    b=a++ + ++a + a++;
    printf("%d",b);
    but the output for this code is 18.

    why?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    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.

    Comment

    • AjayGohil
      New Member
      • Apr 2019
      • 83

      #3
      Hi,

      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.

      Comment

      • lewish95
        New Member
        • Mar 2020
        • 33

        #4
        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) {
        printf("\nOverf low\n");
        break;
        }
        b >>= 1; // Halve b
        a += a; // Double a - avoid using multiplication
        }
        printf("\nProdu ct = %u\n", product);

        Comment

        Working...