Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
July 19th, 2013, 12:28 AM
 MiguelC
Contributing User

Join Date: Jul 2013
Posts: 30
Time spent in forums: 10 h 16 m 46 sec
Reputation 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
July 19th, 2013, 12:50 AM
 dwise1_aol
Contributing User

Join Date: Jan 2003
Location: USA
Posts: 6,830
Time spent in forums: 3 Months 18 h 14 m 4 sec
Reputation Power: 2199
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.

 Viewing: Dev Shed Forums > Programming Languages > C Programming > For loop function