Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this if statement require brackets?

Tags:

c

if-statement

Usually, if I follow an if statement with a single statement, I won't need brackets. For example:

if (condition) statement1; statement2;

statement2 will run in any case. But that doesn't happen here:

for (j = 0; j < size; j++) {
    if (size % 2) if (j % 2) *(minmat + j) *= -1.0;        
    else {
        …
    }
}

The else statement is supposed to associate with the first if statement, but it in fact associates with the second. To correct it, I have to do this:

for (j = 0; j < size; j++) {
    if (size % 2) { if (j % 2) *(minmat + j) *= -1.0; }
    else {
        …
    }
}

But why does that happen, when in the first case it's “implied” that the second if statement is inside brackets?

like image 940
Korgan Rivera Avatar asked Jan 08 '23 08:01

Korgan Rivera


1 Answers

An else statement will associate with the most recent if. You could also correct it like this:

for(j=0; j<size; j++{
    if(size%2) if(j%2) *(minmat+j) *= -1.0; else;        
    else {
        .
        .
        .
    }
}
like image 110
Ron Kuper Avatar answered Jan 15 '23 20:01

Ron Kuper