在有效的c++中使用赋值

Is assigning a value while using it valid c++?

本文关键字:赋值 c++ 有效      更新时间:2023-10-16

我有一个布尔值,每次使用它都需要翻转,因为代码相当简单,每隔一行我就翻转布尔值。我摆弄了一下,想出了这个(甚至更简单的例子)

#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    bool flippy = 0;
    cout << (flippy = !flippy) << "n";
    cout << (flippy = !flippy) << "n";
    cout << (flippy = !flippy) << "n";
    cout << (flippy = !flippy) << "n";
    system("PAUSE");
    return 0;
}

它像预期的那样产生1 0 1 0,但看起来有点奇怪,这是语言的有效使用吗?

是有效的。这不是我所说的好风格

您的代码当然有效。下面以bitset为例进行说明。

#include <iostream>
#include <bitset>
using namespace std;
int main()
{
    bitset<1> myBit;
    cout << myBit << endl;
    cout << myBit.flip() << endl;
    cout << myBit.flip() << endl;
    cout << myBit.flip() << endl;
}