Here’s the offending code in question:
if (xflg)
index = m * nxy + l*nx + k;
fprintf(stdout,"%.1f",index);
else
index = m * nxy + k*ny + l;
The “if” and “else” sections of this if
statement originally had one line each, so adding braces wasn’t strictly necessary. But when you added the call to fprintf
, that changed things.
Since the are no braces after if
, the index = m * nxy + l*nx + k;
line consists of the entire if
part. The printf
that follows is not part of the if
and is a separate statement. Then when the compiler sees the else
, there’s no corresponding if
because the prior if
is complete.
This can be fixed by adding the braces:
if (xflg) {
index = m * nxy + l*nx + k;
fprintf(stdout,"%.1f",index);
} else {
index = m * nxy + k*ny + l;
}
You should always add braces to any if
, else
, for
, while
, or do
block, even if the body is only one line. That prevents errors like this from happening.
You were lucky in this case that failing to add braces resulted in a compiler error. If you didn’t have an else
part in this example, the code would compile and the printf
would always run. Then you’d be scratching your head to figure out why.
As for the printf
warning, index
is of type int
, so you need to use the proper format specifier to print it which is %d
.
1
solved error: ‘else’ without a previous ‘if’ with fprintf [closed]