Hacker News new | ask | show | jobs
by spacemanaki 5024 days ago
Ok, pardon my ignorance, and I know this is really getting out into the pedantry weeds, but that seems like a slightly bizarre post, at best misleading, at worst even wrong.

Why would anyone chose A in that example? Does using pre- and post- increment really result in different behavior for that example in C#? In other words, do these really produce different output:

    for(int i = 0; i < 5; ++i) {
        Console.WriteLine(i);
    }

    for(int i = 0; i < 5; i++) {
        Console.WriteLine(i);
    }
Answers to this question on StackOverflow indicate not: http://stackoverflow.com/questions/484462/difference-between...

It seems like the example might have been supposed to be:

    for(int i = 0; i < 5; ) {
        Console.WriteLine(i++);
    }
Furthermore, is this even correct: "What is the order of operation? Declare, loop body, compare, increment, loop body, compare, increment, .... " Surely for loops in C# are the same in almost every other language, and the comparison happens once before the body is ever executed?

I don't know anything about C#, but I think the suggestion to use one over the other due to performance is pretty poor advice if applied in general. I doubt incrementing an integer is a performance issue in many programs, and if it is you should come to that conclusion after careful profiling. Granted, that post makes the point that based on the C# spec one may be faster than the other, but I still think there are more important things to spend time optimizing.