Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the absolute scope of a for loop with no brackets? [closed]

Tags:

c

scope

I have a program that uses for loops to check conditional statements and run tests on sets of data, and most of these are one liner if statements that could possibly branch off. My question is how does a for loop with brackets decide what is in and out of scope? For example:

A for loop in my program:

for( i =0; i < (sizeof(exact_roots) / sizeof(bn_comlplex)); i++){
        if(fabs(roots[k].re - exact_roots[i].re) < 0.00001 && fabs(roots[i].im - exact_roots[i].im) < 0.00001)
            rootmatch++;
}

are brackets needed in this case? Would the for loop treat the third line as apart of the for loop or discard it and give me a compile error?

what about an extreme case of a for loop with no brackets, how does the loop handle it?

for(i = 0; i < num; i++)
    if(something)
        ....
    else //is this still considered apart of the loop?
        ....
like image 427
Syntactic Fructose Avatar asked Dec 27 '22 12:12

Syntactic Fructose


2 Answers

for(i = 0; i < num; i++)
    if(something)
        ....
    else //is this still considered apart of the loop?
        ....

Yes, it's still part of the loop. The entire if () .... else ... construct is one statement.

But using braces relieves you of the worry. With braces, it's immediately clear what the scope is.

like image 191
Daniel Fischer Avatar answered May 29 '23 22:05

Daniel Fischer


Only the next statement is part of the loop.

In your example the if ... else ...; is one statement.

like image 23
Mark Byers Avatar answered May 29 '23 22:05

Mark Byers