Programming Languages – Why Are Semicolons and Commas Interchanged in For Loops?

loopsprogramming-languagessyntax

In many languages (a wide list, from C to JavaScript):

  • commas , separate arguments (e.g. func(a, b, c)), while
  • semicolons ; separate sequential instructions (e.g. instruction1; instruction2; instruction3).

So why is this mapping reversed in the same languages for for loops:

for ( init1, init2; condition; inc1, inc2 )
{
    instruction1;
    instruction2;
}

instead of (what seems more natural to me)

for ( init1; init2, condition, inc1; inc2 )
{
    instruction1;
    instruction2;
}

?

Sure, for is (usually) not a function, but arguments (i.e. init, condition, increment) behave more like arguments of a function than a sequence of instructions.

Is it due to historical reasons / a convention, or is there a good rationale for the interchange of , and ; in loops?

Best Answer

So why in the same languages such mapping is reversed for for loops.

Technically, the mapping is not "reversed".

  • The things separated by commas are not parameters. In (at least) C++ and Java, they can be declarations, so they are not even expressions.
  • The things separated by semicolons are not (single) statements either.

In reality what we have here is a different syntactic context where the same symbols are being used differently. We are not comparing like with like, so there is no mapping, and no strong argument for a consistent mapping based on semantic consistency.

So why not do it the other way around?

Well I think the reasons come from the "natural" meaning of , and ;. In English written language, a semicolon is "stronger" break than a comma, and the glyph for semicolon is more visible than a comma. Those two things combine to make current arrangement seem (to me!) to be more natural.

But the only way to know for sure why the syntax choice was made would be if the C designers could tell us what they were thinking back in ~1970. I doubt that they have a clear memory of technical decisions made that far back in time.


Is it due to historical reasons / a convention

I'm not aware of any language before C that used a C-like syntax for "for" loops:

  • Donal Fellows notes that BCPL and B didn't have an equivalent construct.

  • The FORTRAN, COBOL and Algol-60 (and Pascal) equivalents were less expressive, and had syntaxes that did not resemble C "for" syntax.

But languages like C, C++ and Java that came after C all clearly borrow their "for" syntax from C.

Related Topic