Why does the if statement require parentheses?

Usually, if I follow instructions ifwith a single expression, I do not need parentheses. For instance:

if (condition) statement1; statement2;

statement2will work anyway. But this does not happen:

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

An operator elsemust be associated with the first operator if, but in fact it is associated with the second. To fix this, 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 this happen when in the first case it is “implied” that the second statement ifis inside the brackets?

+4
source share
5 answers

The else statement will be associated with the last if. You can also fix this as follows:

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

dangling else. , , , else if. , , . , , .

+3

C99:

6.8.4.1 if

...

3 An else if, .

,

if(size%2) if(j%2) *(minmat+j) *= -1.0;        
else {
    .
    .
    .
}

:

if(size%2)
{
   if(j%2) *(minmat+j) *= -1.0;        
   else {
    .
    .
    .
  }
}

:

if(size%2)
{
   if(j%2) {
      *(minmat+j) *= -1.0;
   }
   else {
    .
    .
    .
  }
}
+1

, , "" . :

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

An else if.

+1

elseis an operator that is sticky to if, than a ifdifferent if. Therefore, he "sticks" to the nearest, if. It is just like multiplying before adding.

This is a rule that makes sense, because otherwise nested ifs without parentheses would become problematic.

0
source

All Articles