• 0

[C]Post/Pre Increment/Decrement Question


Question

Please could someone clearly explain the difference between the Post/Pre Increment/Decrement that is used in C quite often. For example

SomeVariable++;

SomeVariable--;

or
++SomeVariable;

--SomeVariable;

What is the difference exactly and do they do different things ? Thanks in Advance :)

Link to comment
Share on other sites

6 answers to this question

Recommended Posts

  • 0

Postfix evaluates to the value before increment/decrement while prefix evaluates to the value after increment/decrement. Consider:

i = 2;

printf("%d\n", i++); // prints 2

// i == 3

i = 2;

printf("%d\n", ++i) // prints 3

// i == 3

Link to comment
Share on other sites

  • 0

i++ increment after evalutation it means

int i=0, j=0;

j=i++;

j=0, i=1

i is assigned before incremented

int i=0, j=0;

j=++i;

j=1, i=1

j is incremented, then assigned to j

another difference is that ++i is faster than i++ (intel compliler manual said)

Link to comment
Share on other sites

  • 0
i++ increment after evalutation it means

j=0, i=1

i is assigned before incremented

j=1, i=1

j is incremented, then assigned to j

another difference is that ++i is faster than i++ (intel compliler manual said)

584747061[/snapback]

Yeah, i++ requires it making a temporary object in memory.

Pre vs. Post Increment/Decrement

Prefer pre-increment and -decrement to postfix operators. Postfix operators (i++) copy the existing value to a temporary object, increment the internal value, and then return the temporary. Prefix operators (++i) increment the value and return a reference to it. With objects such as iterators, creating temporary copies is expensive compared to built-in ints.

http://bdn.borland.com/article/0,1410,28278,00.html

Edited by kjordan2001
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.