0

Possible Duplicate:
Why can you return from a non-void function without returning a value without producing a compiler error?

Why does gcc 4.6.1 compile the following function without a return statement?

uint32_t& siof_solution() {
   static uint32_t example = (uint32_t) 7; // Doesn't really matter
   // return example;
}

It returns 1. I seen't it.

Community
  • 1
  • 1
sholsapp
  • 15,542
  • 10
  • 50
  • 67
  • 2
    Hey, it gives you a warning, isn't that enough? There was a switch to stop compilation on warning... – Griwes Feb 16 '12 at 20:29
  • I've seen similar cases with the Visual C++ compiler also. Where a function was declared with a return value, I forgot to put the return statement and somehow it compiled and returned a value! In my case the return value was garbage which was interpreted as true. Not sure why. – Nerdtron Feb 16 '12 at 20:29
  • 2
    **Always** compile with all warnings enabled. Don't post until you've tried to compile with all warnings. – Kerrek SB Feb 16 '12 at 20:29
  • Woops -- didn't see that quesiton ildjarn. Thanks (voted to close). – sholsapp Feb 16 '12 at 20:31

2 Answers2

9

C++ functions aren't required to return a value even if they say they do. If they don't, the result is undefined behavior. In your case, through Sheer Dumb Luck the code seems t be working, but it's not portable and not safe. This could crash, return a garbage pointer, cause a debug error, etc.

I think the reason for this decision is mostly backwards-compatibility with C, though I'm not sure.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
0

Return check is turned off somehow. I don't even remember if it is required in C++ at all. The returned value in your case is memory garbage.

Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385