#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    30
    Rep Power
    1

    For loop function


    int x;

    for(x=0;x<100;x++);

    In here, why does the for loop have ";" inside its parenthesis instead of ","?
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,091
    Rep Power
    2222
    Read up on the syntax of the for statement. It has three expressions (from memory): the initialization expression, the condition expression, and the update expression, in order of appearance. Each expression is delimited from the others by a semicolon. That is the syntax.

    Why not a comma? Well, you can indeed have commas, but only within an expression. For example:
    for (x=0, y=0; y== 42, x < 100; x++, y+=2);

    The comma operator allows you to add more expressions to an expression. This comes in very handy in the initialization expression in that it allows you to initialize more than just one variable. And it comes in very handy in the update expression in that it allows you to update more than one variable.

    The condition expression is where it gets kind of weird. Every expression evaluates to a value; an assignment evaluates to the value being assigned, BTW. When you use the comma operator, the value that the entire expression evaluates to is the last expression, so for x++, y+=2 that value would be the y+2 that you assigned back to y. OK, now what is the value of y== 42, x < 100? That value is 1 (or at least non-zero) if x<100 or 0 if x>=100. What does the y==42 contribute? Absolutely nothing; I just threw it in there to show use of the comma operator even though it served no actual purpose. The only sub-expressions before the final one that are of any use are the ones that have a side-effect (eg, initializing a variable or updating one). And, as it turns out, it's only the evaluated value of the condition expression that is ever used.

    So then, in brief review and directly addressing your question: semicolons delimit expressions; commas do not.

IMN logo majestic logo threadwatch logo seochat tools logo