Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment operator inside array

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++];
like image 314
Loki San Hitleson Avatar asked Dec 13 '15 12:12

Loki San Hitleson


People also ask

Can we use increment operator in array?

Increment operator is placed before the operand in preincrement and the value is first incremented and then operation is performed on it.

What is ++ i and i ++ in C?

In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. That means both i++ and ++i will be equivalent.

Can we increment and decrement a array?

In a single operation, an element of the array can either be incremented or decremented by 1. Print the minimum number of operations required.


2 Answers

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.

like image 146
LogicStuff Avatar answered Sep 19 '22 13:09

LogicStuff


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.

like image 29
StephenG - Help Ukraine Avatar answered Sep 19 '22 13:09

StephenG - Help Ukraine