“返回”是否可以在C中返回多个值? [英] Can 'return' return multiple values in C?

查看:165
本文介绍了“返回”是否可以在C中返回多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C ++—返回x,y;

这里有一段代码可以在C中完美执行

Here's a piece of code that executes perfectly in C.

int a=3,b=4,x,y;
x=a+b;
y=a*b;
return(x,y);

此函数返回12。有人可以解释。

This function returns 12. Can someone please explain.

推荐答案

这是因为您(无意中)使用了逗号运算符,其值为包含的最后一个表达式的值。您可以列出任意多个表达式,并用逗号运算符分隔,结果始终是最后一个表达式的结果。这与返回无关;您的代码可以这样重写:

This is because you (inadvertently) use the comma operator, whose value is that of the last expression included. You can list as many expressions as you like, separated by the comma operator, the result is always that of the last expression. This is not related to return; your code can be rewritten like

int tmp = (x, y); // x = 7, y = 12 -> tmp is assigned 12
return tmp;

[已更新] 您通常不需要在列表中使用括号,但是在这里您可以这样做,因为赋值运算符的优先级比逗号高-对@Draco指出来表示敬意。

[Updated] You don't usually need brackets around the list, but here you do, due to the assignment operator having a higher precedence than comma - kudos to @Draco for pointing it out.

这篇关于“返回”是否可以在C中返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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