C中函数的返回值 [英] Return value of function in C

查看:76
本文介绍了C中函数的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int ret(char *)
{
    //nothing    
}

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

为什么函数ret返回垃圾值???

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

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

在上面的函数中,如果我没有错,my_strlen 应该总是返回垃圾值当条件失败时(即当它到达 '\0' 时),因为没有 else 情况或任何返回错误情况的语句.所以对于任何有效的字符串,它应该总是返回 1 + 垃圾值.但它没有.它工作正常.它给出了 Any 的精确长度细绳.为什么它不像函数ret"那样返回垃圾值???请解开我的疑惑.任何帮助将不胜感激.谢谢..

in the above function , if i am not wrong , my_strlen should always return Junk value when condition fails (i.e 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..

推荐答案

在这两种情况下,都是未定义行为.来自 C99 标准(N869 草案)的 6.9.1 函数定义部分,第 12 条:

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.

这篇关于C中函数的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆