3

g++ 5.4.1 under Linux (UBUNTU 16.04) will compile the following program without errors or warnings:

#include <iostream>

std::string foo(){
    int a= 1;
    a++;
}

int main(){
    std::cout << foo();
    return 0;
}

Obviously the return statement in "foo()" is missing and the program in my computer core-dumps. I am asking myself why the absence of the return statement is not even warned at compilation time? Did I miss something?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 6
    There's a reason you should always build with more warnings enabled. I always use at least `-Wall -Wextra -pedantic` when building with GCC. Usually I also add `-Werror` to turn warnings into errors. – Some programmer dude Oct 18 '17 at 08:02
  • 1
    Compile your code with `-Wall`. – vishal-wadhwa Oct 18 '17 at 08:03
  • 1
    As for why extra compiler flags are needed, it's because the compiler doesn't have to produce a "diagnostic" (i.e. a message) about it, as per the C++ specification. It's still a very good thing to have, so the compiler added it as an extra flag that could be enabled. – Some programmer dude Oct 18 '17 at 08:11
  • @Ron In this simple case, yes. But you can easily extend the example so that the warning disappears again. – ComicSansMS Oct 18 '17 at 08:22

2 Answers2

2

I suspect you didn't compile with warnings enabled.

Compile like this:

g++ -Wall -Wextra main.cpp

and you should get:

warning: no return statement in function returning non-void [-Wreturn-type]

PS: This is irrelevant to the version of GCC.


The compiler doesn't have to produce a diagnostic message, that's why warnings flags had to be enabled in order for the compiler to complain. Read more in Why does this C++ snippet compile (non-void function does not return a value).

gsamaras
  • 71,951
  • 46
  • 188
  • 305
1

You did not include the appropriate warning flags. Chances are you only used something like:

g++ source.cpp

Add: -Wall, -pedantic, -Wextra and similar flags:

g++ -std=c++14 -Wall -Wextra -pedantic source.cpp

Live example
That being said you should also include the <string> header:

#include <string>

and not rely on free string rides from <iostream>.

Ron
  • 14,674
  • 4
  • 34
  • 47