View Poll Results: a++ or ++a?

Voters
35. You may not vote on this poll
  • a++

    23 65.71%
  • ++a

    10 28.57%
  • a = a + 1

    1 2.86%
  • a = 1 + a

    0 0%
  • never uses them

    1 2.86%

Thread: a++ or ++a

  1. #31
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Originally posted by Prelude
    >This could be optimized away, thus making a=a++ faster.
    Why would you want to optimize undefined behavior?
    Huh? After you've moved it from 'a' to eax, there is no need to move it back from eax to 'a'. It's already there. I didn't mean removing both lines if that's what you hinted ^^.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  2. #32
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I didn't mean removing both lines if that's what you hinted ^^.
    What I was referring to was the fact that both the C and C++ standards clearly state that modifying a variable more than once between sequence points results in undefined behavior. Thus, a=a++ is incorrect unless your compiler supports it, then it's simply non-portable. If you changed the lines to
    Code:
    a++;
    and
    Code:
    ++a;
    Then your comments would be more correct, though you would have to rebuild the assembly output as it would be different.
    My best code is written with the delete key.

  3. #33
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Oh, I see. Didn't think of that. I didn't want to use only a++ and ++a in case the return value would be omitted. Anyway, I redid the test like this (I see now what that double mov-statement was ^^). The result is the same. Both ways have the same instructions set, only in a different order.

    Code:
    void Inc_1()
    {
    	int a = 0;
    	int b = a++; //Line 4
    }
    
    void Inc_2()
    {
    	int a = 0;
    	int b = ++a; //Line 10
    }
    
    int main()
    {
    	Inc_1();
    	Inc_2();
    	return 0;
    }
    Code:
    ; Line 4
    	mov	eax, DWORD PTR _a$[ebp]
    	mov	DWORD PTR _b$[ebp], eax
    	mov	ecx, DWORD PTR _a$[ebp]
    	add	ecx, 1
    	mov	DWORD PTR _a$[ebp], ecx
    Code:
    ; Line 10
    	mov	eax, DWORD PTR _a$[ebp]
    	add	eax, 1
    	mov	DWORD PTR _a$[ebp], eax
    	mov	ecx, DWORD PTR _a$[ebp]
    	mov	DWORD PTR _b$[ebp], ecx
    Last edited by Magos; 11-29-2003 at 11:32 AM.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed