我见过有人使用带有多个值的return语句的实例。例如:return 8, 10, 6;
据我所知,实际上仅返回这些值之一。这样使用return
有什么好处?
具体来说,这个问题出现在我的作业中。
语句:
return 2 * 3 + 1, 1 + 5;
返回值____。
我知道它总是返回6,那么为什么我会这样写呢?
请问这是一个简单的问题。我还是编程新手。
答案 0 :(得分:1)
语句return 2 * 3 + 1, 1 + 5;
返回值 6 。
这是C ++中逗号运算符的技巧。你可以在这里读更多关于它的内容: https://en.cppreference.com/w/cpp/language/operator_other
逗号运算符基本上是由逗号分隔的表达式的列表,它们将从左到右进行求值,最后一项的结果将被视为整个逗号运算符。
这是一个简单的示例,演示逗号运算符的工作原理。
int foo() {
int i = 1;
return i += 2, i++, i + 5; // This is a comma operator with three items
// i += 2 will be evaluated first, then i == 3
// i++ will be evaluated second, then i == 4
// i + 5 will be evaluate last, and the result is 9
// the result of the last item is returned by the return statement
}
int main() {
std::cout << foo();
return 0;
}
此代码显示9。
答案 1 :(得分:-1)
这样做时,您避免在功能块中使用数学运算,这会使您的函数像工作3次一样,结果将是您想要的函数