C: What is the difference between ++i and i++?

前端 未结 21 2113
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 06:04

In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?

相关标签:
21条回答
  • 2020-11-21 06:05

    The following C code fragment illustrates the difference between the pre and post increment and decrement operators:

    int  i;
    int  j;
    

    Increment operators:

    i = 1;
    j = ++i;    // i is now 2, j is also 2
    j = i++;    // i is now 3, j is 2
    
    0 讨论(0)
  • 2020-11-21 06:06

    They both increment the number. ++i is equivalent to i = i + 1.

    i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluated, whereas i++ increments the number after the expression is evaluated.

    Example:

    int i = 1;
    int x = i++; //x is 1, i is 2
    int y = ++i; //y is 3, i is 3
    
    0 讨论(0)
  • 2020-11-21 06:07

    Please don't worry about the "efficiency" (speed, really) of which one is faster. We have compilers these days that take care of these things. Use whichever one makes sense to use, based on which more clearly shows your intent.

    0 讨论(0)
  • 2020-11-21 06:10

    a=i++ means a contains current i value a=++i means a contains incremented i value

    0 讨论(0)
  • 2020-11-21 06:12

    ++i (Prefix operation): Increments and then assigns the value
    (eg): int i = 5, int b = ++i In this case, 6 is assigned to b first and then increments to 7 and so on.

    i++ (Postfix operation): Assigns and then increments the value
    (eg): int i = 5, int b = i++ In this case, 5 is assigned to b first and then increments to 6 and so on.

    Incase of for loop: i++ is mostly used because, normally we use the starting value of i before incrementing in for loop. But depending on your program logic it may vary.

    0 讨论(0)
  • 2020-11-21 06:12

    ++i: is pre-increment the other is post-increment.

    i++: gets the element and then increments it.
    ++i: increments i and then returns the element.

    Example:

    int i = 0;
    printf("i: %d\n", i);
    printf("i++: %d\n", i++);
    printf("++i: %d\n", ++i);
    

    Output:

    i: 0
    i++: 0
    ++i: 2
    
    0 讨论(0)
提交回复
热议问题