Pre vs Post Increment / Decrement

    int32 a = 1;
    int32 b = ++a;

So am I the only one who thinks this is just too confusing?

You are declaring 2 integers, but the declaration of the second then overrides the declaration of the first.
Why would you allow coding to do this?
What if you need the original value of a?

I guess you can do

    int32 a = 1;
    int32 b = a +1 ;

So then why bother with a ++ method?

And again why use += instead of just +?

Then you use postfix

int32 a = 1;
int32 b = a++; // a = 2, b = 1

All of this is for when you want to increment a and also use it in another context e.g. passing the value to a function or initialising another variable. So if you ever want to do

b = a;
++a;

// another example

foo(a);
++a;

You can just write

b = a++;

// another example

foo(a++);

Or if you want to write

++a;
b = a;

// another example

++a;
foo(a);

You can write

b = ++a;

// another example

f(++a);

In other words, if you want to use a variable and then increment it you can use postfix. If you want increment a variable and then use it you can use prefix.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms