Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the following do-while loop is valid?

Tags:

c

loops

do-while

The loop is as follows:

do;
while(1);

Why the above loop is not giving a syntax error?

I am using mingw gcc compiler

like image 883
kevin gomes Avatar asked Dec 02 '22 17:12

kevin gomes


1 Answers

That code looks like it was written to obfuscate its meaning but if we look at the draft C99 standard section 6.8.5 Iteration statements, the grammar for do while is:

do statement while ( expression ) ;

and statement can be an expression statement which in turn can be a null statement which is what ; is. So it is the same as:

do
  ;
while(1);

we can see from section 6.8.3 Expression and null statements paragraph 3 says:

A null statement (consisting of just a semicolon) performs no operations.

like image 103
Shafik Yaghmour Avatar answered Dec 11 '22 17:12

Shafik Yaghmour