pre-increment vs post-increment

it makes sense that at least with larger data structures or classes that overload these operators, calling op++ returns by value and ++op returns by reference, so the latter is faster and avoids the complexly constructed temporary.

However, references returned also have to be put into temporaries. So what about built-in data types like int and float? these are 4 bytes, and references to them are also 4 bytes (I hear they can be 2 bytes depending on how far the address is). So wouldn't that make int++ and ++int cost the exact same since a reference to an int is the exact same size as an int?
Last edited on
closed account (zb0S216C)
caibbor wrote:
"However, references returned also have to be put into temporaries. So what about built-in data types like int and float?"

Intrinsic types such as "int" and "float" and are well-known by the compiler are more likely to become subject to optimisations than user-defined types.

caibbor wrote:
"these are 4 bytes, and references to them are also 4 bytes (I hear they can be 2 bytes depending on how far the address is)."

Hold your horses, here; you're treading on implementation-defined information.

Firstly, the size of intrinsic data-types varies from compiler-to-compiler, so I'll go ahead and assume the size of "float" and "int" are 4-bytes on your system.

Secondly, the term "reference" in C++ is reserved by the "reference" type, in which case, references may or may not reserve memory for the storage of its referent. Though, because you said "can be 2 bytes depending on how far the address is", I'm going to assume that you're referring to a "pointer". If the latter is the case then you should know that on modern systems, the days of "far" and "near" pointers have since passed and that pointers generally (but not always) have a consistent size.

caibbor wrote:
"So wouldn't that make int++ and ++int cost the exact same since a reference to an int is the exact same size as an int?"

Hard to tell. The post-fix operators have one additional parameter, which is usually unused, that adds to the overhead of the call to the operator. However, a smart compiler will not push unused parameters onto the stack.

You're right, both post- and pre-fix operators of intrinsic types create copies of its operand, but those copies are justified to give you the expected output. When comparing the post- and pre-fix operators, you'll notice that the post-fix operators will create 1 additional temporary copy of the operand than the pre-fix operators, thereby making pre-fix operators more efficient.

More over, each compiler may perform post- and pre-fix operations differently; some implementations may perform faster than others. Based on the optimisation scheme your have in place for your program, your operators may perform differently.

Wazzak
Last edited on
Topic archived. No new replies allowed.