0

I'm sorry, I'm still a noob at C. I wonder why post and prefix have different effect in "printf" but have the same effect in "for"or maybe in other loop ?

example :

#include <stdio.h>
main()
{
    int number = 0;
    printf("%d.\n", ++number); //It prints 1
    return 0;
}


...............
    printf("%d.\n", number++); //it prints 0
...............

but in "for"

#include<stdio.h>
main()
{
    int number;
    for (number = 0; number < 5; ++number);
    {
        printf("%d\n", number); //it prints 0,1,2,3,4
    }
    return 0;
}
.............
    for (number = 0; number < 5, number++);
    {
       printf("%d\n", number); //it prints 0,1,2,3,4
    }
.........................
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • If you don't use the value of the expression, it doesn't matter. Do you see a difference between discarding a value then adding 1 to the variable and adding 1 to a variable and the discarding the value? – a3f Mar 20 '15 at 18:30
  • Yes, i can see the diffrence. – Blue Tomato Mar 20 '15 at 18:35

2 Answers2

0

In for, result of third expression is thrown away, so it doesn't matter if it is number or number+1. Only the side effect of changing the value of number variable remains, and it is same for post- and pre-increment.

But when you pass it as function argument, value of expression matters, and that is different. Note that for is not a function, btw!

hyde
  • 60,639
  • 21
  • 115
  • 176
0

From section 6.5.2.4 Postfix increment and decrement operators of http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf:

The result of the postfix ++ operator is the value of the operand. After the result is obtained, the value of the operand is incremented.

However, from 6.5.3.1 Prefix increment and decrement operators:

The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation.

There is a reason why the C standard has both operators. As you can see from the standard, ++x returns (x+1) and sets x = (x+1) while x++ returns x and sets x = (x+1).

As the other answer explained, the for loop is not a function call and does not use the value of the expression at all for the third expression so it doesn't matter (but do note that for the second expression the value of the expression matters!).

juhist
  • 4,210
  • 16
  • 33