The simplest statement is the empty statement, also known as a null statement. A null statement is a single semicolon:
; // null statement
A null statement is useful where the language requires a statement but the program’s logic does not. Such usage is most common when a loop’s work can be done within its condition. For example, we might want to read an input stream, ignoring everything we read until we encounter a particular value:
// read until we hit end-of-file or find an input equal to sought
while (cin >> s && s != sought)
; // null statement
This condition reads a value from the standard input and implicitly tests cin
to see whether the read was successful. Assuming the read succeeded, the second part of the condition tests whether the value we read is equal to the value in sought
. If we found the value we want, the while
loop is exited. Otherwise, the condition is evaluated again, which reads another value from cin
.