Date: Mon, 23 Oct 2000 09:58:12 -0700 (PDT) From: Hannah C. Tang To: cse142-section-bf@cs.washington.edu Subject: [Section BF] Nested "if"s Wondering about the "not all control paths return a value" compiler warning? Keep reading below .... Hannah ---------- Forwarded message ---------- Date: Mon, 23 Oct 2000 09:52:56 -0700 (PDT) From: Hannah C. Tang To: Subject: Re: Nested "if"s In C (and C++) whitespace doesn't matter. I can write programs that compile which look like: int main(void) {int i = 0; if(i > 0) printf("Hello!\n"); return 0;} Whitespace just makes programs easier to read: int main(void) { int i = 0; if(i > 0) printf("Hello!\n"); return 0; } The compiler knows what goes into your if-statements only through the use/non-use of curly-braces, not whitespace. Sometimes, the compiler will give warnings about "not all control paths return a value." What this means is that your if-else/if-else-if's don't have a final "else": if(cond1) ... return 1; else if(cond2) ... return 2; else if(cond3) ... return 3; /* End of function */ You, as the programmer, may know that only one of cond1, cond2, and cond3 may be true, but from the compiler's perspective, it is possible that neither cond1, cond2, nor cond3 may be true. So your function could (in the compiler's point of view) not have a return value! Thus it flags the above statements as a warning. If you draw the control flow diagram, it's a little clearer what's happening: (True is left, false is right) ______cond1______ | | | ______cond2______ return 1| | | return 2 | | | ______cond3______ | | | | | | return 3 | | | |_______________| | | | | |_______________| | | |_______________| | /* End of function */ Notice that the rightmost branch of your control-path doesn't have a return value. If you added a final "else" to your code: if(cond1) ... return 1; else if(cond2) ... return 2; else if(cond3) ... return 3; else ... return 0; /* End of function */ Then you would end up with a control-flow diagram which would look like: (True is left, false is right) ______cond1______ | | | ______cond2______ return 1| | | return 2 | | | ______cond3______ | | | | | | return 3 return 0 | | |_______________| | | | | |_______________| | | |_______________| | /* End of function */ Notice that all control-flow paths now return a value. If you're having problems with if-else statements, I'd encourage you to draw a control-flow diagram; they're a great way to make sure that what you intend matches up with what you typed. Hannah ----- Original Message ----- Date: Sat, 21 Oct 2000 21:43:14 -0700 (PDT) From: To: CS 142 TA Subject: Nested "if"s Hi Hannah, How do I know that the compiler will see my nested "if"s as such? Does it only rely on indentation (along with the use of braces '{' and '}'?)