C++ -- 返回 x,y; 重点是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2539458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:51:24  来源:igfitidea点击:

C++ -- return x,y; What is the point?

c++csyntaxreturn-valuecomma-operator

提问by Earlz

I have been programming in C and C++ for a few years and now I'm just now taking a college course in it and our book had a function like this for an example:

我已经用 C 和 C++ 编程几年了,现在我刚刚参加了大学课程,我们的书有一个这样的函数作为例子:

int foo(){
  int x=0;
  int y=20;
  return x,y; //y is always returned
}

I have never seen such syntax. In fact, I have never seen the ,operator used outside of parameter lists. If yis always returned though, then what is the point? Is there a case where a return statement would need to be created like this?

我从未见过这样的语法。事实上,我从未见过在,参数列表之外使用的运算符。如果y总是返回,那么有什么意义?是否有需要像这样创建 return 语句的情况?

(Also, I tagged C as well because it applies to both, though my book specifically is C++)

(另外,我也标记了 C,因为它适用于两者,尽管我的书特别是 C++)

采纳答案by Joel

The comma operator is primarily used in forstatements like so:

逗号运算符主要用于如下for语句:

for( int i=0, j=10; i<10; i++, j++ )
{
    a[i] = b[j];
}

The first comma is not a comma operator, it's part of the declaration syntax. The second isa comma operator.

第一个逗号不是逗号运算符,它是声明语法的一部分。第二个逗号运算符。

回答by Justin Ethier

According to the C FAQ:

根据C 常见问题解答

Precisely stated, the meaning of the comma operator in the general expression

e1 , e2

is "evaluate the subexpression e1, then evaluate e2; the value of the expression is the value of e2." Therefore, e1 had better involve an assignment or an increment ++ or decrement -- or function call or some other kind of side effect, because otherwise it would calculate a value which would be discarded.

准确地说,逗号运算符在一般表达式中的含义

e1,e2

是“计算子表达式 e1,然后计算 e2;表达式的值就是 e2 的值。” 因此,e1 最好涉及赋值或递增 ++ 或递减——或函数调用或其他某种副作用,否则它会计算出一个将被丢弃的值。

So I agree with you, there is no pointother than to illustrate that this is valid syntax, if that.

所以我同意你的看法,除了说明这是有效的语法之外别无他法。

If you wanted to return both values in C or C++ you could create a structcontaining xand ymembers, and return the struct instead:

如果你想在 C 或 C++ 中返回两个值,你可以创建一个struct包含xy成员,并返回结构:

struct point {int x; int y;};

You can then define a type and helper function to allow you to easily return both values within the struct:

然后,您可以定义一个类型和辅助函数,以允许您轻松地返回以下两个值struct

typedef struct point Point;

Point point(int xx, int yy){
  Point p;
  p.x = xx;
  p.y = yy;
  return p;
}

And then change your original code to use the helper function:

然后更改您的原始代码以使用辅助函数:

Point foo(){
  int x=0;
  int y=20;
  return point(x,y); // x and y are both returned
}

And finally, you can try it out:

最后,您可以尝试一下:

Point p = foo();
printf("%d, %d\n", p.x, p.y);

This example compiles in both C and C++. Although, as Mark suggests below, in C++ you can define a constructor for the pointstructure which affords a more elegant solution.

此示例可在 C 和 C++ 中编译。虽然,正如马克在下面建议的那样,在 C++ 中,您可以为point结构定义一个构造函数,从而提供更优雅的解决方案。



On a side note, the ability to return multiple values directly is wonderful in languages such as Python that support it:

附带说明一下,在 Python 等支持它的语言中,直接返回多个值的能力非常棒:

def foo():
  x = 0
  y = 20
  return x,y # Returns a tuple containing both x and y

>>> foo()
(0, 20)

回答by Thomas Padron-McCarthy

The comma in parameter lists is just there to separate the parameters, and is not the same as the comma operator. The comma operator, as in your example, evaluates both x and y, and then throws away x.

参数列表中的逗号只是用来分隔参数,与逗号运算符不同。逗号运算符,如您的示例,计算 x 和 y,然后丢弃 x。

In this case, I would guess that it is a mistake by someone who tries to return two values, and didn't know how to do it.

在这种情况下,我猜想这是一个试图返回两个值但不知道该怎么做的人的错误。

回答by jcoder

This doesn't really answer the original question at all but might be of interest to some people, but if you wanted to it to return both in C++ you'd need to write it like this (and would need a c++0x compiler)

这根本没有真正回答原始问题,但某些人可能会感兴趣,但是如果您希望它在 C++ 中同时返回,您需要像这样编写它(并且需要一个 c++0x 编译器)

tuple<int, int> foo()
{
    int x = 0;
    int y = 20;
    return make_tuple(x, y);
}

The access it like this -

像这样访问它 -

tuple<int, int> data = foo();
int a = get<0>(data);
int b = get<1>(data);

回答by kennytm

 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;
 }

:p

:p

回答by Joel Rondeau

Much like everyone commenting here thinks it is pointless and I don't disagree, just looking at the example, I'm going to make a guess that's not much better:

就像这里评论的每个人都认为这是毫无意义的,我不反对一样,仅看示例,我将做出一个并没有好到哪里去的猜测:

The writer was getting a compiler warning about x not being used within the function, and this was an easy way to get the warning to go away.

作者收到一个编译器警告,提示 x 未在函数中使用,这是消除警告的简单方法。

回答by Daniel Daranas

This is the comma operator (,).

这是逗号运算符 (,)

Both expressions x and y are evaluated. The result of the overall expression is y, i.e., the latter value.

计算表达式 x 和 y。整体表达式的结果是y,即后一个值。

It's hard to say why it is used here. I guess, for demonstration purposes. Clearly the function could be refactored to:

很难说为什么在这里使用它。我想,出于演示目的。显然,该函数可以重构为:

int foo()
{
  return 20;
}

回答by florg

This syntax can be used to save additional scope brackets of an if- statement. E.g. normally you would write the following:

此语法可用于保存if- 语句的附加范围括号。例如,通常您会编写以下内容:

if (someThing == true)
{
    a = 1;
    b = 2;
    return true;
}

This can be replaced by the following:

这可以替换为以下内容:

if (someThing == true)
    return a = 1, b = 2, true;

I think the usage of this coding style is rather motivated by the urge for posing than for writing clean code.

我认为这种编码风格的使用是出于摆姿势的冲动,而不是为了编写干净的代码。

回答by Andy White

That looks like a terrible example of code. It might be valid syntax in C/C++, but I can't think of a reason why you'd ever want to do that.

这看起来是一个糟糕的代码示例。它可能是 C/C++ 中的有效语法,但我想不出你为什么想要这样做的原因。

If you want to return both x and y, a better way to do it in C++ would be to define a "Point" class or struct with x and y properties, and return that. Another option would be to pass in x and y by reference, then set the values appropriately in the method.

如果您想同时返回 x 和 y,在 C++ 中更好的方法是定义一个具有 x 和 y 属性的“Point”类或结构,然后返回它。另一种选择是通过引用传入 x 和 y,然后在方法中适当地设置值。

If the method is going to just return y, I would just "return y;". If x needs to be "evaluated" before the return statement, it should be done on a separate line.

如果该方法只返回 y,我将只“返回 y;”。如果 x 需要在 return 语句之前“求值”,则应在单独的行中完成。

回答by David Thornley

There is no point in that return statement.

该 return 语句没有任何意义。

If xwere declared volatile, it would force an access (since at least in C++ references to volatilevariables are considered to be externally observable behavior), but it isn't.

如果x被声明volatile,它将强制访问(因为至少在 C++ 中对volatile变量的引用被认为是外部可观察的行为),但事实并非如此。

If, instead of x, there was some sort of calculation with side effects, it would do that calculation and then return y. However, a non-volatilexhas no side effects. The implementation is not required to execute any code that has no side effects or externally observable behavior. The comma operator executes whatever is on the left side of the comma, disregards the result, and executes and keeps the value of the right side (except that it's free to ignore the left side of the operator in this case).

如果,而不是x,有某种带有副作用的计算,它会进行该计算,然后返回y。然而,非volatilex没有副作用。该实现不需要执行任何没有副作用或外部可观察行为的代码。逗号运算符执行逗号左侧的任何内容,忽略结果,并执行并保留右侧的值(除了在这种情况下可以随意忽略运算符的左侧)。

Therefore, the return x, y;statement is the exact same thing as return y;. If xwasn't just a completely meaningless thing to execute, it would be stylistically better to write it as x; return y;, which is the precise same thing. It wouldn't be nearly as confusing that way.

因此,该return x, y;语句与return y;. 如果x它不只是一个完全没有意义的东西来执行,那么将它写成在风格上会更好x; return y;,这是完全相同的东西。这样就不会那么混乱了。