Thursday 18 April 2013

printf("%d %d %d",a,a++,++a);


What will be output if you will compile and execute the following c code?

void main(){
  int a=10;
  printf("%d %d %d",a,a++,++a);
}


(A) 12 11 11

(B) 12 10 10

(C) 11 11 12

(D) 10 10 12

(E) Compiler error


________________________________________
Explanation:
In c printf function follows cdecl parameter passing scheme. In this scheme parameter is passed from right to left direction.

So first ++a will pass and value of variable will be a=10 then a++ will pass now value variable will be a=10 and at the end a will pass and value of a will be a=12.

21 comments:

  1. the output is 12 11 12
    now tell the reason

    ReplyDelete
    Replies
    1. Its an illegal operation. look here http://stackoverflow.com/questions/1270370/printfd-d-d-n-a-a-a-output

      Delete
    2. it is compiler dependent expression.

      Delete
    3. This comment has been removed by the author.

      Delete
    4. For the increment/decrement operator the associativity is from right to left.
      ++a -> 12
      a++ -> 11
      a -> 12

      Delete
    5. Basically,What happens here is, same value is modified more than once and it is not defined then answer will be compiler dependent.

      Delete
  2. int i=10;
    printf("%d %d %d",++i,i++,i);
    what will be output of this plz explain

    ReplyDelete
    Replies
    1. Output will be 12 10 12 ,use www.codechef.com

      Delete
  3. Output will be 12 11 12 ,use www.codechef.com

    ReplyDelete
  4. What will be the Output:

    main()
    {
    int arr[]={0,1,2,3,4};

    int i,*ptr;
    for(ptr=arr+4,i=0;i<=4;i++)
    printf("%d",ptr[-i]);

    }

    plz rply

    ReplyDelete
  5. output is 12 11 12.. plz tell why

    ReplyDelete
  6. output is 12 11 12.. plz tell why

    ReplyDelete
  7. void main()
    {
    int a=10;
    printf("%d",a);
    printf("%d",a++);
    printf("%d",++a);
    getch();
    }
    this program will get u following o/p
    101012

    ReplyDelete
  8. Hello everyone,
    According to the advanced compilers, Evaluation of printf() statement takes places from right to left
    ++a = 11
    a++ = 11// after completing value is 12
    a = 12
    This is correct my dears.
    If You have any more doubts in regarding this question or else on anything else in any language
    Please feel free to mail me.
    kanumururajeshreddy@gmail.com

    ReplyDelete
  9. What will be the output of this question
    Void main()
    {
    int a= 120;
    printf("%d"+1,a);
    }

    ReplyDelete