++ operator

float var;
var++;

I wonder if this is valid.If Im not wrong, i++ is more efficient than i=i+1 but is this also true for float variables?
It works just fine. ++ operator just increments integral variable by one. So, as long as you're using it on a number your good :D
This also works for other data types:
1
2
3
4
5
6
7
char letter = 'a';

	for( int i = 0; i < 26; ++i )
	{
		std::cout << "Letter: " << letter << '\n';
		++letter;
	}

letter: a
letter: b
letter: c
...
letter: x
letter: y
letter: z
> If Im not wrong, i++ is more efficient than i=i+1

For standard types, both are equally efficient.
1
2
3
4
5
6
7
8
int foo( int i )
{
    i = i +1 ;
    i += 1 ;
    int j = ++i ;
    int k = i++ ;
    return i + j - k ;
}

and
1
2
3
4
int bar( int i )
{
    return i + 4 ;
}

will generate identical code; the compiler knows everything about what is going on.

On my implementation, the code for both is:
1
2
3
	movl	4(%esp), %eax
	addl	$4, %eax
	ret




This is a difference with the following:
1
2
++i;
i++;


1
2
3
4
	int i = 5;
	int j = 5;

	std::cout << i + j++ << '\n';

Output:
10


1
2
3
4
	int i = 5;
	int j = 5;

	std::cout << i + ++j << '\n';

Output:
11


The first one will add i and j together, and then increment j; whereas the second one will increment j before the addition takes place.

EDIT:
I also think that someone on here once told me that ++i was more efficient. I've used it since then.
But which ever way it's used, you have to think about the outcome. As in the above code.
Last edited on
> someone on here once told me that ++i was more efficient.
> I've used it since then.

It is a good habit to get into - never use the prefix version of the increment or decrement operators unless the value before the increment/decrement is needed. For user defined types, ++iterator could very well be more efficient than iterator++. For any type, ++i would not be less efficient than i++.
Topic archived. No new replies allowed.