SITERAW

What is the difference between ++i and i++??

Author Message
Mike # Posted two weeks ago
Mike

Hi, I'm reading the chapter on loops in C and I've come across the ++ variable incrementation.

What is the difference between ++i and i++ in C?

Can you give me a few examples to illustrate?

I understand that one add +1 before the execution, and the other after, but I don't see how that affects the loop itself?

Ads
Darth JarJar # Posted one week ago
Darth JarJar

They all say they're "reading the chapter" lol. Really? Reaaaaally? It's not like the explanation is hard to find, is it?

Clara # Posted yesterday
Clara

@Darth JarJar: You're supposed to be nice to noobs ;)

What don't you understand, @Mike?

Phoenix # Posted yesterday
Phoenix

In C, ++i and i++ both increment the value of i by 1. They differ only in when the increment happens relative to the expression they're used in.

As you guessed:

  • ++i is pre-increment: increment first, then use the value.
  • i++ is post-increment: use the value first, then increment.

A simple example:

int i = 4;
int a = ++i; // a = 5, i = 5
int b = i++; // b = 5, i = 6

i is incremented before it's assigned to a, but after it's assigned to b.

Valter # Posted yesterday
Valter

++i is also more efficient, although modern compilers will convert the "usual" i++.

It's not bad practice to write:

for (int i = 0; i < 5; ++i)
printf("%d ", i);

I guess people are just more used to i++ as it's almost always presented as such in textbooks and the like.

Kegon # Posted two hours ago
Kegon

Think fast:

int i = 1, j = 10;
int a = j + ++i + j++;

What is j/a^2 ?

Mike # Posted two hours ago
Mike

Thanks yall :D I guess Siteraw.com is the best site on the internet after all!

Valter # Posted one hour ago
Valter

(Approximate) assembly code of ++i:

mov eax, 5
inc eax
mov ebx, eax

You essentially reverse the last two lines with i++.

Phoenix # Posted one hour ago
Phoenix

@Mike: On the Internets you fking heretic.

Darth JarJar # Posted 7 minutes ago
Darth JarJar

@Phoenix: It just confirms what I was saying, bro can't read

Post a reply

Please be kind and courteous in your replies. Don't roast others for no reason.