Ear*_*rlz 46 c c++ syntax return-value comma-operator
我已经用C和C++编程了几年,现在我刚刚开始学习大学课程而且我们的书有一个这样的函数作为一个例子:
int foo(){
int x=0;
int y=20;
return x,y; //y is always returned
}
Run Code Online (Sandbox Code Playgroud)
我从未见过这样的语法.事实上,我从未见过在,参数列表之外使用的运算符.如果y总是返回,那么重点是什么?是否有需要像这样创建return语句的情况?
(另外,我也标记了C,因为它适用于两者,尽管我的书特别是C++)
Jus*_*ier 51
根据C FAQ:
准确地说,逗号运算符在一般表达式中的含义
e1,e2
是"评估子表达式e1,然后评估e2;表达式的值是e2的值." 因此,e1最好涉及赋值或增量++或减量 - 或函数调用或其他一些副作用,否则它将计算一个将被丢弃的值.
所以我同意你的观点,除了说明这是有效的语法之外没有其他意义,如果那样的话.
如果要在C或C++中返回两个值,可以创建一个struct包含x和y成员,并返回结构:
struct point {int x; int y;};
Run Code Online (Sandbox Code Playgroud)
然后,您可以定义类型和辅助函数,以便在以下内容中轻松返回两个值struct:
typedef struct point Point;
Point point(int xx, int yy){
Point p;
p.x = xx;
p.y = yy;
return p;
}
Run Code Online (Sandbox Code Playgroud)
然后更改原始代码以使用辅助函数:
Point foo(){
int x=0;
int y=20;
return point(x,y); // x and y are both returned
}
Run Code Online (Sandbox Code Playgroud)
最后,你可以尝试一下:
Point p = foo();
printf("%d, %d\n", p.x, p.y);
Run Code Online (Sandbox Code Playgroud)
此示例在C和C++中编译.虽然如Mark所示,在C++中,您可以为point结构定义构造函数,从而提供更优雅的解决方案.
另外,在支持它的Python语言中,直接返回多个值的能力非常好:
def foo():
x = 0
y = 20
return x,y # Returns a tuple containing both x and y
>>> foo()
(0, 20)
Run Code Online (Sandbox Code Playgroud)
Joe*_*oel 20
逗号运算符主要用于如下for语句:
for( int i=0, j=10; i<10; i++, j++ )
{
a[i] = b[j];
}
Run Code Online (Sandbox Code Playgroud)
第一个逗号不是逗号运算符,它是声明语法的一部分.第二个是逗号运算符.
这根本不能回答原始问题,但可能对某些人感兴趣,但如果你想用C++返回它们,你需要像这样写它(并且需要一个c ++ 0x编译器) )
tuple<int, int> foo()
{
int x = 0;
int y = 20;
return make_tuple(x, y);
}
Run Code Online (Sandbox Code Playgroud)
这样访问 -
tuple<int, int> data = foo();
int a = get<0>(data);
int b = get<1>(data);
Run Code Online (Sandbox Code Playgroud)
struct Point {
int x, y;
Point(int x_) : x(x_), y(0) {}
Point(const Point& p) : x(p.x), y(p.y) {}
Point operator, (int y_) const { Point p=*this; p.y = y_; return p; }
};
Point get_the_point () {
int x = 0;
int y = 20;
return (Point)x, y;
}
Run Code Online (Sandbox Code Playgroud)
:p