Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are empty expressions legal in C/C++?

int main()
{
  int var = 0;; // Typo which compiles just fine
}
like image 999
sharkin Avatar asked May 05 '09 11:05

sharkin


4 Answers

How else could assert(foo == bar); compile down to nothing when NDEBUG is defined?

like image 134
j_random_hacker Avatar answered Oct 19 '22 09:10

j_random_hacker


This is the way C and C++ express NOP.

like image 20
mouviciel Avatar answered Oct 19 '22 11:10

mouviciel


I'm no language designer, but the answer I'd give is "why not?" From the language design perspective, one wants the rules (i.e. the grammar) to be as simple as possible.

Not to mention that "empty expressions" have uses, i.e.

for (i = 0; i < INSANE_NUMBER; i++);

Will dead-wait (not a good use, but a use nonetheless).

EDIT: As pointed out in a comment to this answer, any compiler worth its salt would probably not busy wait at this loop, and optimize it away. However, if there were something more useful in the for head itself (other than i++), which I've seen done (strangely) with data structure traversal, then I imagine you could still construct a loop with an empty body (by using/abusing the "for" construct).

like image 32
Dan Fego Avatar answered Oct 19 '22 11:10

Dan Fego


You want to be able to do things like

while (fnorble(the_smurf) == FAILED)
    ;

and not

while (fnorble(the_smurf) == FAILED)
    do_nothing_just_because_you_have_to_write_something_here();

But! Please do not write the empty statement on the same line, like this:

while (fnorble(the_smurf) == FAILED);

That’s a very good way to confuse the reader, since it is easy to miss the semicolon, and therefore think that the next row is the body of the loop. Remember: Programming is really about communication — not with the compiler, but with other people, who will read your code. (Or with yourself, three years later!)

like image 26
Thomas Padron-McCarthy Avatar answered Oct 19 '22 10:10

Thomas Padron-McCarthy