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++];
Increment operator is placed before the operand in preincrement and the value is first incremented and then operation is performed on it.
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.
In a single operation, an element of the array can either be incremented or decremented by 1. Print the minimum number of operations required.
Please explain these operations.
array[++i];
- first increments i
, then gives you element at the incremented index
equivalent to:
++i; // or i++
array[i];
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With