Increment operator inside array

20,108

Solution 1

Please explain these operations.

  1. array[++i]; - first increments i, then gives you element at the incremented index

    equivalent to:

    ++i; // or i++
    array[i];
    
  2. array[i++]; - also first increments i, but postfix operator++ returns i's value before the incrementation

    equivalent to:

    array[i];
    ++i; // or i++
    

They increment a variable inside array.

No, they don't. You could say they increment i within the call to array subscript operator.

Solution 2

The ++i increments i before evaluating it.

The i++ inrements i after evaluating it.

If i=1 then array[++i] sets i=2 and then fetches array[2].

If i=1 then array[i++] fetches array[1] then sets i=2.

The post- and pre- operations happen after or before the expression they are involved in is evaluation.

I generally discourage the use of post and pre increment operators in expressions. They can lead to confusion at best and bugs at worst.

Consider what x = array[++i] + array[i--] ; should be. See how easy it is to confuse the programmer ( or the poor devil who has to fix your code ? :-) ).

Post and pre increment and decrement operations can also produce problems in macros, as you end up with the potential for an operation to be duplicated multiple times, especially with macros.

It is simpler and produces easier to maintain code to avoid post and pre increments in expressions, IMO.

Solution 3

So, you know i++ and ++i increment i with 1. Also, this instruction returns i, so you can put this somewhere in your code where you need the value of i.

The difference between the 2 is that i++ is post increment, and ++i is pre increment. What does this mean?

Well, let's say i is 6. When you do:

array[i++]
array[i]

You will actually be doing:

array[6]
array[7]

Because you use post increment: first return value, then increment i.

If you do:

array[++i]
array[i]

You'll basically be doing:

array[7]
array[7]

Because you use pre increment: first increment i, then return its value.

Now try to find what your code does ;-)

Hope this helps.

Solution 4

array[++i]; - increments the value of i and then uses the incremented value as an index into array

array[i++]; -indexes into the array and then increments the value of i

Share:
20,108
Loki San Hitleson
Author by

Loki San Hitleson

Updated on July 09, 2022

Comments

  • Loki San Hitleson
    Loki San Hitleson almost 2 years

    I have a C program which does queue operations using an array. In that program, they increment a variable inside array. I can't understand how that works. So, please explain these operations:

    array[++i];
    array[i++];
    
  • Loki San Hitleson
    Loki San Hitleson over 8 years
    So, this is normal operation. It won't affect the array elements right?
  • LogicStuff
    LogicStuff over 8 years
    No, it won't - elements, not indices.