This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Compiler didn't error on function with no return statement


On 21/06/13 16:40, Andy Falanga (afalanga) wrote:

Who said it's not legal C++?

I inferred that.  Obviously, I shouldn't have.  David said that it
was legal C and so I made the jump into not legal C++.


And you *do* get a warning with -Wreturn-type, but you don't get
an error because that would reject legal programs:

My understanding was in error.  That is why I thought that I should
get a warning message from the C++ compiler (without the extra step
of an option to the compiler).


void f();

bool g() { f(); }

Is this an error?  What if f() never returns?

In C++11 we could mark f() with [[noreturn]] (like GCC's
__attribute((noreturn))) but just because a function isn't marked
noreturn doesn't mean it does return.

True, but that does seem to be rather poor design (I know you're
giving me an example).  Probably, the language supports this because
of some need which I've not run into and am unaware of its merits.

Thanks for the info.

Andy


Most embedded systems have something like this:

int main(void) {
	initialise_everything();
	while (true) {
		run_everything();
	}
}

Putting a "return 0;" at the end would be unreachable code, which you don't want.

Anyway, the point is that for various reasons (technical, historical, simplicity of implementation, or complexity of checking) there are plenty of things that are legal C but have undefined behaviour. Returning from a non-void function without specifying the return value is one such case. And like many similar cases, gcc can warn about it in almost all circumstances - /if/ you enable the warning flags.

So learn to use -Wall, -Wextra, and many of the other flags. They are a very easy way to keep your code safe and clean (well, /safer/ and /cleaner/), and they help catch many small bugs or typos.




Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]