c++ - Why does flowing off the end of a non-void function without returning a value not produce a compiler error? -


ever since realized many years ago, doesn't produce error default, (in gcc @ least) i've wondered why?

i understand can issue compiler flags produce warning, shouldn't error? why make sense non-void function not returning value valid?

an example requested in comments:

#include <stdio.h> int stringsize() { }  int main() {     char cstring[5];     printf( "the last char is: %c\n", cstring[stringsize()-1] );      return 0; } 

...compiles.

c99 , c++ standards don't require functions return value. missing return statement in value-returning function defined (to return 0) in main function.

the rationale includes checking if every code path returns value quite difficult, , return value set embedded assembler or other tricky methods.

from c++11 draft:

§ 6.6.3/2

flowing off end of function [...] results in undefined behavior in value-returning function.

§ 3.6.1/5

if control reaches end of main without encountering return statement, effect of executing

return 0; 

note behaviour described in c++ 6.6.3/2 not same in c.


gcc give warning if call -wreturn-type option.

-wreturn-type warn whenever function defined return-type defaults int. warn return statement no return-value in function return-type not void (falling off end of function body considered returning without value), , return statement expression in function return-type void.

this warning enabled -wall.


just curiosity, code does:

#include <iostream>  int foo() {    int = 5;    int b = + 1; }  int main() { std::cout << foo() << std::endl; } // may print 6 

this code has formally undefined behaviour, , in practice it's calling convention , architecture dependent. on 1 particular system, 1 particular compiler, return value result of last expression evaluation, stored in eax register of system's processor.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -