Search code examples
cincrementpost-incrementpre-increment

The difference between n++ and ++n at the end of a while loop? (ANSI C)


this is probably a dumb question but I just can't figure it out. It has to do with the differences between n++ and ++n (which I thought I understood but apparently not).

#include <stdio.h>
#include <math.h>

long algorithmA(int n);
long algorithmB(int n);

int main(){
    long A, B;
    A = B = 0;
    int n = 1;
    while(A >= B){
        A = algorithmA(n);
        B = algorithmB(n);
        n++;
    }
    printf("At n = %d, Algorithm A performs in %ld seconds & "
           "Algorithm B performs in %ld seconds.", n, A, B);

}

long algorithmA(int n){
    return pow(n,4) * 86400 * 4;
}

long algorithmB(int n){
    return pow(3,n);
}

Here you can probably tell I'm trying to see at what point Algorithm A outperforms Algorithm B. The functions and units of time were given to me in a homework problem.

Anyways, I always thought that the order of "++" would not matter at the end of a while loop. But if I put ++n instead of n++, I get the wrong answer. Can somebody explain why?

Edit: Well it WAS showing 24 with ++n and 25 with n++, but it must have been for another reason. Because I just checked now and there is no difference. Thanks for your patience and time guys, I just wish I knew what I did!


Solution

  • The only difference between n++ and ++n is that n++ yields the original value of n, and ++n yields the value of n after it's been incremented. Both have the side effect of modifying the value of n by incrementing it.

    If the result is discarded, as it is in your code, there is no effective difference.

    If your program is behaving differently depending on whether you write

    n++;
    

    or

    ++n;
    

    it must be for some other reason.

    In fact, when I compile and execute your program on my system, I get exactly the same output in both cases. Adding newlines to the output format, I get:

    At n = 25, Algorithm A performs in 114661785600 seconds &
    Algorithm B performs in 282429536481 seconds.
    

    You haven't told us what output you're getting. Please update your question to show the output in both cases.