逗号运算符有什么作用?

Mat*_*att 40 c c++ operators comma-operator

以下代码在C/C++中的作用是什么?

if (blah(), 5) {
    //do something
}
Run Code Online (Sandbox Code Playgroud)

its*_*att 66

应用逗号运算符,值5用于确定条件的真/假.

它将执行blah()并返回某些东西(大概),然后使用逗号运算符,5将是唯一用于确定表达式的真/假值的东西.


注意,对于blah()函数的返回类型(未指定),可以重载,运算符,使得结果不明显.


jop*_*jop 45

如果逗号运算符没有重载,则代码类似于:

blah();
if (5) {
  // do something
}
Run Code Online (Sandbox Code Playgroud)

如果逗号运算符过载,则结果将基于该函数.

#include <iostream>
#include <string>

using namespace std;

string blah()
{
    return "blah";
}

bool operator,(const string& key, const int& val) {
    return false;
}

int main (int argc, char * const argv[]) {

    if (blah(), 5) {
        cout << "if block";
    } else {
        cout << "else block";
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

(编辑显示逗号运算符重载方案.感谢David Pierre对此进行评论)


小智 20

我知道这种代码应该做的一件事:它应该让编码器解雇.我会有点害怕在这样写的人旁边工作.


Ecl*_*pse 13

在病态情况下,它取决于逗号运算符的作用...

class PlaceHolder
{
};

PlaceHolder Blah() { return PlaceHolder(); }

bool operator,(PlaceHolder, int) { return false; }

if (Blah(), 5)
{
    cout << "This will never run.";
}
Run Code Online (Sandbox Code Playgroud)