about ++ operator

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • virus
    New Member
    • Nov 2006
    • 9

    about ++ operator

    I have Red Hat Linux enterprise-4 edition on my pc. Problem is this.


    int main()
    {
    int i=1;
    i=i++;
    printf("%d",i);
    return 0;
    }
    Out put of this program is 1 in my pc & 2 in turbo c. what is the correct result.
    Please help me.
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    Originally posted by virus
    I have Red Hat Linux enterprise-4 edition on my pc. Problem is this.


    int main()
    {
    int i=1;
    i=i++;
    printf("%d",i);
    return 0;
    }
    Out put of this program is 1 in my pc & 2 in turbo c. what is the correct result.
    Please help me.
    The value of i after
    i=i++;
    depends on whether the increment of i occurs before or after the assignment. in C it's unspecified; in some implementations the value will be 1, in some it will be 2. Simillarly
    (i * j) + (i * j++)
    will the value of j in (i * j) be that before or after the increment in (i * j++) ? again it is unspecified.
    The advice is do not use a variable more than once in an expression if one or more of the references has a ++ or -- operator attached to it.

    Comment

    • Ganon11
      Recognized Expert Specialist
      • Oct 2006
      • 3651

      #3
      Indeed. The statement

      i=i++;

      is like saying

      i = i = i + 1;

      Why not just say

      i++;

      and be done with it? There's no need to reassign i to itself, since ++ stands for

      i = i + 1;

      Comment

      • horace1
        Recognized Expert Top Contributor
        • Nov 2006
        • 1510

        #4
        have a look at the C FAQ on URL
        http://c-faq.com/

        in particular the discussion about "i=i++;" on URL
        http://c-faq.com/expr/ieqiplusplus.ht ml

        and " will a[i] = i++; work" on URL
        http://c-faq.com/expr/evalorder1.html

        there is also a good discussion on expressions and "side effects" on URL
        http://www.csci.csusb. edu/dick/c++std/cd2/expr.html

        where it states in paragraph 4
        "4 Except where noted, the order of evaluation of operands of individual
        operators and subexpressions of individual expressions, and the order
        in which side effects take place, is unspecified. ....."

        Comment

        Working...