Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

c - No loop condition in for and while loop

while(cond) // fine
for(;cond;) //fine

but when I remove the conditional part

while() //syntax compilation error 
for(;;) //Infinite loop

How these loops are internally implemented ? Or,how does compiler (parser) know that empty condition in while is error and in for as Infinite?

I didn't find anything about this particularly, I think guys like me (who are beginner) in C might have same confusion

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The standard requires that the omitted condition for for loop is replaced by a non-zero constant:

From C11 6.8.5.3: (emphasis mine)

6.8.5.3 The for statement

1 The statement for ( clause-1 ; expression-2 ; expression-3 ) statement behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body. The expression expression-3 is evaluated as a void expression after each execution of the loop body. If clause-1 is a declaration, the scope of any variables it declares is the remainder of the declaration and the entire loop, including the other two expressions; it is reached in the order of execution before the first evaluation of the controlling expression. If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.134)

2 Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

Since there's no such requirement for while loop (if the condition is omitted), I believe, it's left to the implementation of compiler.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...