Back to questions
JuniorTheoryOccasional
What does the program print?
#include <iostream>
int kind(int x) {
if (x > 0)
if (x > 10)
return 2;
else
return -1;
return 1;
}
int main() { std::cout << kind(5) << ' ' << kind(-5); }-1 1
- Expecting
1 -1, as the indentation suggests: anelsebelongs to the nearestifwithout anelse, hereif (x > 10), and indentation changes nothing. - Expecting a compile error: the nearest-
ifrule leaves no ambiguity, so Clang and GCC only warn and suggest braces.
- How would you place braces in
kindso that it returns-1for everyx <= 0? - Which compiler warning flags an ambiguous
else, and what fix does it suggest?