简体   繁体   English

C函数的返回值

[英]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 ??? 为什么函数ret返回一个垃圾值?

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. 在上面的函数中,如果我没有记错,则在条件失败时(即,只要达到'\\ 0'),my_strlen应该始终返回垃圾值,因为没有其他情况或任何用于错误情况的return语句。 So for any valid string it should always return 1 + junk value. 因此,对于任何有效的字符串,它应始终返回1 +垃圾值。 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 ??? 为什么它不像函数“ ret ”那样返回垃圾值呢? 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: 根据C99标准的第6.9.1节(N869草案)的功能定义 ,第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". 真正的答案是,在Eclipse / Microsoft C编译器上,您的代码将以“警告”进行编译。 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; 之所以会产生垃圾,是因为有一个叫做“堆栈”的东西,并且因为没有发出return 0;而没有将整数放置在它上面return 0; (or non-zero if you want) statement. (如果需要,则为非零)语句。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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