Use of increments in C

Asked

Viewed 272 times

3

What is the difference in the use of increments in C language, considering an integer N?

N++
++N
N--
--N

3 answers

4


The expression ++n increments the value and then returns the incremented value.

And in the expression n++ returns first the value of n and then the value is increased. It is a subtle difference and the copier works in the same way for the decrease n-- or --n.

In a loop for you can use the ++n, is slightly faster. Already, n++ in a loop for create an extra copy of its value that will be thrown away, but this is no reason not to use the n++ in the loop for, unless you are programming for a hardware where memory is extremely limited, so it would be justifiable to use ++n in the loop for.

Source: https://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i

  • 1

    Just adding that the ++n behavior is easier to predict and so it is usually recommended above the n++.

  • "In a for loop you can use ++n, it’s slightly faster." Usually the compiler optimizes these cases and the end result is equivalent to n++

1

The increment has the variation for each case you want to use. ex:

int x = 10;
int y = 10;
printf("%i",x++); // imprime 10
printf("%i",x);  // imprime 11
printf("%i",++y); // imprime 11
printf("%i",y); // imprime 11

increment or decrement after the variable, returns the variable before changing the value, before the variable, makes the change and then returns.

1

These are the concepts of pre and post increment. And the same applies for decrement also.

Being:

y = 0;
x = 10;

Preincrement

y = ++x;
y = 11;

Equals the following allocation:

x++;
y = x;

That is, increases the x and then assigns the new value of x to y. ________________________________________________________________________

Post-increment

y = x++;
y = 10;

Equals the following allocation:

y = x;
x++;

That is, assigns the value of x to y, and then increase x.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.