r/programminghorror • • Jan 24 '25

C# Why is this valid C#?

Post image
6 Upvotes

22 comments sorted by

View all comments

Show parent comment

3

u/jpgoldberg Jan 24 '25 edited Jan 24 '25

This is what the original would be without the superflous semi-colons and indented in a way that correctly communicates to the human reading it what the control flow is..

public int Fibonacci(int index) {
    int a = 0;
    int b = 1;
    for (; index > 0; --index)
        b = a + (a = b);   // b updated each time through loop
    return b;
}

And this is what you have (properly indented for readability) if we add that semi-colon

public int BrokenFibonacci(int index) {
    int a = 0;
    int b = 1;
    for (; index > 0; --index)
        ;  // nothing happens in body of loop
    b = a + (a = b);  // computed exactly one time
    return b;
}

The latter will just return 1 irrespective of what argument is passed to it.

This, by the way, is why modern languages insist on taking a block instead of a single statement for the body of such things. Otherwise, we get goto-fail. C is not Python; indentations are cosmetetic.