简体   繁体   中英

Return value of function in C

int ret(char *)
{
    //nothing    
}

int main(void)
{
   printf("%d\n",ret("foo"));
}

Why does the Function ret returns a garbage value ???

and

int my_strlen(char *s)
{
   if(*s)
      return 1 + my_strlen(s + 1); // or my_strlen(s+1) + 1;
}

in the above function , if i am not wrong , my_strlen should always return Junk value when condition fails (ie whenever it reaches to '\\0') as there is no else case or any return statement for false case. So for any valid string it should always return 1 + junk value. But it doesn't . It works fine. It gives exact length of Any string. Why doesn't it return junk value like the function " ret " does ??? Kindly clear my doubts. Any help would greatly be appreciated. Thanx..

In both cases, it is undefined behaviour . From section 6.9.1 Function definitions of the C99 standard (draft N869), clause 12:

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

A subset of undefined behaviour is to appear to work correctly, which is what is witnessed in the second code snippet.

Sorry for the general lack of respect of your question.

The real answer is that on Eclipse/Microsoft C compiler your code compiles with a "warning". I copied your code and fixed what was probably a typo on your part:

   // Here, I added the variable X
   int ret(char *X)
   {
       //nothing
   }

   int main(void)
   {
      printf("%d\n",ret("foo"));
   }

and got the following message:

   c:~\eclipsecdt\compilererrormsg\main.c(15) : warning C4716: 'ret' : must return a value

Hopefully, this message explains what you need to do to fix your code. The reason why you are getting garbage is because of something called "the stack" and the fact that an integer has not been place onto it because you have not issued a return 0; (or non-zero if you want) statement.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM