What is a null statement in C?
Solution 1
From the msdn page:
The "null statement" is an expression statement with the expression missing. It is useful when the syntax of the language calls for a statement but no expression evaluation. It consists of a semicolon.
Null statements are commonly used as placeholders in iteration statements or as statements on which to place labels at the end of compound statements or functions.
know more: https://msdn.microsoft.com/en-us/library/1zea45ac.aspx
And explain a typical use of it.
When you want to find the index of first occurrence of a certain character in a string
int a[50] = "lord of the rings";
int i;
for(i = 0; a[i] != 't'; i++)
;//null statement
//as no operation is required
Solution 2
A null statement is a statement that doesn't do anything, but exists for syntactical reasons.
while ((*s++ = *t++))
; /* null statement */
In this case the null statement provides the body of the while loop.
or (disclaimer: bad code)
if (condition1)
if (condition2)
dosomething();
else
; /* null statement */
else
dosomethingelse();
In this case the inner else and null statement keeps the outer else from binding to the inner if.
Solution 3
From C11, §6.8.4.1, 6.8.3 Expression and null statements:
A null statement (consisting of just a semicolon) performs no operations.
The standard also provides a couple of common uses of it:
EXAMPLE 2 In the program fragment
char *s; /* ... */ while (*s++ != '\0') ;
a null statement is used to supply an empty loop body to the iteration statement.
6 EXAMPLE 3 A null statement may also be used to carry a label just before the closing } of a compound statement.
while (loop1) { /* ... */ while (loop2) { /* ... */ if (want_out) goto end_loop1; /* ... */ } /* ... */ end_loop1: ; }
Elliyas A.
Updated on July 09, 2022Comments
-
Elliyas A. almost 2 years
I want to know exactly, what is a null statement in C programming language? And explain a typical use of it.
I found the following segment of code.
for (j=6; j>0; j++) ;
And
for (j=6; j>0; j++)