[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Bug#119440: g++: Compiler does not give any errors when a function fails to return required value



> Not exactly. Here is what I'm talking about:

I know there are cases that could be detected, like the one you
produce below. However, as soon as you have a function call in the
function, or an operator call, you cannot determine reliably anymore
whether the function will return.

> Are you a g++ author?

Why does this matter? I'm certainly not going to change g++ in the way
you desire.

> The problem with the above code is that g++ will compile the code as
> if it is normal, and when you run it, it will just spew out a random
> result.

That is not a problem. There are many ways to invoke undefined
behaviour in C++, and very few of them can be checked reliably.

> It's also evident that there cannot be any exit or throw out of the
> function. If there isn't a single control path that contains a
> return statement, you can't expect the function to ever return
> anything, it is a programming error.

Not necessarily. It could be an infinite loop.

> so if a function has a non void return type but only serves to exit
> or throw exception (like your example) that is also precisely a
> programming error.

Maybe. However, what about

int foo(int i){
  if(i>0)
    return 2*i;
  abort();
}

The purpose of this function is *not* to "just exit", but still it
won't run fall off its end.

> It might be valid in C++ specification (is it?)

It is. 6.6.3, [stmt.return]/1 says

# Flowing off the end of a function is equivalent to a return with no
# value; this results in undefined behavior in a value-returning
# function.

> but the compiler should warn about it.

The compiler does, with -Wreturn-type.

> I would think that the compiler should give a warning by default in
> this case, otherwise it is misleading to the programmer who is
> accustomed to the "typesafety" of the language.

The language is typesafe. There is a difference between type errors
(i.e. accessing memory through a wrong type), and accessing
uninitialized objects. Falling off the end of a function is but one
way to create "uninitialized" objects. Another, more common case is

int x(){
	int x;
	return x;
}

This still returns an arbitrary value. However, the compiler won't
even detect with with -Wall, unless -O is specified: Detecting the
problem requires data flow analysis, which isn't done without
optimization.

> In other words, "-Wreturn-type" does not seem to solve this problem. 

Making -Wreturn-type the default doesn't solve the problem, either,
but makes it worse: The compiler will give many false warnings, which
couldn't be easily turned off.

> I'm reopening this bug. Set the severity to wishlist if you find
> appropriate.

I still propose to close this. GCC maintainers will never accept a
change in this respect.

Regards,
Martin



Reply to: