CHAN
CHAN

Reputation: 145

Any difference between these two while loops?

while ((R_SPI2SR & B_SPIF) != B_SPIF)
{
    SERIAL_SERVICE_WDOG;
};


while ((R_SPI2SR & B_SPIF) != B_SPIF)
{
    SERIAL_SERVICE_WDOG;
}

I like to know what is the purpose in putting semicolon..

Upvotes: 0

Views: 374

Answers (3)

Jim Ferrans
Jim Ferrans

Reputation: 31012

The statement executed by the while loop is the compound statement inside the curly braces. The semicolon is just a gratuitous empty statement. You could have written this loop as:

while ((R_SPI2SR & B_SPIF) != B_SPIF)
    SERIAL_SERVICE_WDOG;

since the compound statement just has a single statement inside it, or as

while ((R_SPI2SR & B_SPIF) != B_SPIF)
{
    SERIAL_SERVICE_WDOG;;;;;;;;;;;;;;;
};;;;;;;;;;;;;;   

which of course is awful style.

An empty statement is used when you have a loop that needs no body.

/* Throw away remaining characters up to the end of line. */
while ( ( c = getchar() ) != '\n')
   ;

You want to watch out for the classic error of ending a loop prematurely:

int i = 1;
int j = 1;
while ( i < 10 );    /* The semicolon here ends the loop... */
    j *= i++;        /* ... so this statement is only executed once. */

Unnecessary semicolons are just clutter, so you should never use them.

Upvotes: 5

AnT stands with Russia
AnT stands with Russia

Reputation: 320361

The semicolon after the first loop is not a part of that loop at all. It is interpreted as a completely independent empty statement that sits between the loops. I.e. your actual loops are seen as absolutely identical by C language.

Upvotes: 6

YeenFei
YeenFei

Reputation: 3208

the only different in the code is the additional semicolon. but the compiled assembly are the same.

Upvotes: 3

Related Questions