increment and decrement problem in c

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • suman das
    New Member
    • Aug 2007
    • 1

    increment and decrement problem in c

    slove this problem

    include<stdio.h >
    include<conio.h >
    void main()
    {
    int i=1;
    printf("%d",i++ *++i);
    getch();
    }
    if the ans is 3 explain it how;
    there is a problem
    it is found that the order of precedence of increment and decrement operator
    with respect to other arithmetic operator is not well define.
    in some computer the result may vary , it may be 3 and 4 both if we use torbo c++ for compilation. same for printing
    printf("%d",i++ *++i*++i)
    result is expected 18 by RL rule by in my torbo c it gives 12 ans
    plz write if u have any rule to sort it out.
  • ilikepython
    Recognized Expert Contributor
    • Feb 2007
    • 844

    #2
    Originally posted by suman das
    slove this problem

    include<stdio.h >
    include<conio.h >
    void main()
    {
    int i=1;
    printf("%d",i++ *++i);
    getch();
    }
    if the ans is 3 explain it how;
    there is a problem
    it is found that the order of precedence of increment and decrement operator
    with respect to other arithmetic operator is not well define.
    in some computer the result may vary , it may be 3 and 4 both if we use torbo c++ for compilation. same for printing
    printf("%d",i++ *++i*++i)
    result is expected 18 by RL rule by in my torbo c it gives 12 ans
    plz write if u have any rule to sort it out.
    The behaivior is undefined whenever you increment a variable more than once. The result can be anything and shouldn't be relied on.

    Comment

    • debojyoti

      #3
      ++ operator has higher priority than *...

      so in case pintf("%d",i++ * ++i);
      the value of i is incremented by 1 in i++ but it is not assigned in i

      in case of ++i value of i is incremented by i and it is assigned in i

      the initial value of i is 1

      try to dry run (i++ * ++i)....in i++ the value of i is incremented...a s the value is not assigned the result of i++ operation is 1

      but the value which in i becomes 2...after ++i operation the value of i becomes 3

      multiply 1 and 3 the result is 3

      apply the same logic in the later problem...hope u will get the correct result

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Look here and here and here and here.

        Comment

        Working...