Matěj Pokorný Matěj Pokorný - 2 months ago 23
C++ Question

Unreachable code, but without any warning

After almost an hour of debugging, I finally discover missing semicolon after one return statement. Here is simplified version

void PrintNumber(int value) {
cout << value << endl;
}

void BuggyFunction(int value)
{
if (value == 0)
return

PrintNumber(value);
}


Yeah, PrintNumber will never be called. But compiler (VS 2015) was silent. Is there a reason for this behaviour?

Answer

Well, technically your function is (due to the missing semicolon) interpreted as follows:

void BuggyFunction(int value) {
    if (value == 0) {
      return PrintNumber(value);
    }
}

Since PrintNumber has also void as a return type, this statement is perfectly syntactically legal, although it doesn't make much sense, obviously.

Note that the C++ compiler doesn't care about indentation. If you want to scope statements and variables correctly, use curly brackets (as I did in the above snippet) to avoid confusion.

Comments