这个具有多个值(变量)的返回语句是如何工作的? [英] How does this return statement with multiple values (variables) works?

查看:90
本文介绍了这个具有多个值(变量)的返回语句是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解一下如何通过价值传递&返回正在C函数中发生。如下所示:

  #include< stdio.h> 

int fun(int ii,int jj)
{
int kk,ll;
kk = ii + jj;
ll = ii * jj;
return(kk,ll);
}

int main()
{
int i = 4,j = 5,k,l;
k = fun(i,j);
l = fun(i,j);
printf(%d%d \\\
,k,l);
返回0;
}

现在显然我没有收到任何错误,当我试图返回2个值通过 fun()



通过 fun() ll 即20(= 4 * 5)而不是 kk 。此外,如果我将 return 语句重写为:

  return(ll ,KK); 

返回的值是 kk 即。 9(= 4 + 5)。

查询:为什么这样呢?

  return(kk,ll); 

您使用逗号运算符。通过逗号运算符的属性,您不会返回两个值,而只是返回逗号运算符的第二个操作数。



详细说明,让我们来检查一下逗号运算符的属性,直接引用标准 C11 ,第6.5.17节,(强调我的


逗号运算符的左操作数被评估为void表达式;它的评估与右操作数的评估之间有一个顺序点。然后评估右操作数; 结果有它的类型和价值

所以,基本上,返回语句就像

  return(kk,ll); 



  return ll; 

希望您能弄清楚其他情况。



main()的推荐签名是 int main(int argc, char * argv [])或至少 int main(void)。


I am trying to get some understanding about how pass by value & return are happening in C functions. I cam across a piece of code as follows:

#include <stdio.h>

int fun(int ii, int jj)
{
 int kk, ll;
 kk = ii + jj;
 ll = ii * jj;
 return (kk,ll);
}

int main()
{
 int i=4, j=5, k, l;
 k = fun(i, j);
 l = fun(i, j);
 printf("%d %d\n", k, l);
 return 0;
}

Now apparently I am not getting any errors when I am trying to return 2 values through fun().

Also, the value that is returned by fun() is ll i.e 20 (=4*5) and not kk. Further, If I rewrite the return statement as :

return (ll,kk);

the value returned is that of kk ie. 9 (=4+5).

Query: Why this is so?

解决方案

In your code, in the return statement

 return (kk,ll);

you're using the comma operator. By the property of the comma operator, you're not returning two values, rather you're returning the second operand of the comma operator only.

To elaborate, let's check the property of the comma operator, directly quoting the standard, C11, chapter §6.5.17, (emphasis mine)

The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.

So, essentially, a return statement like

 return (kk,ll);

is same as

return ll;

Hope you can figure out the other case.


That said, the recommended signature for main() is int main(int argc, char*argv[]) or , at least, int main(void).

这篇关于这个具有多个值(变量)的返回语句是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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