[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

Hash: SHA1

On Wednesday 14 November 2001 02:32, Martin v. Loewis wrote:
> > > A similar algorithm does not exist for reliably determining that a
> > > function falls off its end.
> >
> > What if there is no return statement in a function with a non-void return
> > type?
> Like this?
> int foo(){
>   exit(3);
> }
> Has no return statement, but still doesn't invoke undefined behavior.

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

#include <iostream>

int f(int x)
   int f;
   f = 2;
   for (int i=1; i<=4; i++) {
      f = f + i * x;

int main()
   cout << "f(3)=" << f(3) << endl;

Are you a g++ author?

This illustrates what I'm exactly talking about. IIRC some other compilers 
will complain about the f function not returning any value here. (Have to 
check, though)

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.

g++ compiles this code without giving any warnings by default. However, as 
you can see the f(..) function lacks a return statement. 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. exit or throw 
would be employed in a function only in the case of exceptions, 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. It 
might be valid in C++ specification (is it?), but the compiler should warn 
about it.

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.

In other words, "-Wreturn-type" does not seem to solve this problem. The 
compiler would have to detect whether there is no path that returns a value 
rather than detecting whether there is a path that does not return a value to 
give a useful warning message.

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


- -- 
Eray Ozkural (exa) <erayo@cs.bilkent.edu.tr>
Comp. Sci. Dept., Bilkent University, Ankara
www: http://www.cs.bilkent.edu.tr/~erayo
GPG public key fingerprint: 360C 852F 88B0 A745 F31B  EA0F 7C07 AE16 874D 539C
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org


Reply to: