Reputation: 99
I have this loop here that alternates a boolean.
Here is what I mean:
bool switch = false;
while(true) {
switch = !switch;
std::cout << switch << std::endl;
}
Every time this code loops, the boolean named switch will alternate between true and false.
Something like:
bool switch = false;
while(true) {
std::cout << !switch << std::endl;
}
There is really nothing wrong with this but I would like a one-line solution.
Of course, that doesn't work but something similar to that.
Upvotes: 2
Views: 1475
Reputation: 12749
If you are in the mood for overcomplicating things, here is the "enterprise edition":
#include <iostream>
class SwitchingBool
{
bool state_{};
public:
operator bool() const noexcept { return state_; }
bool operator()() noexcept { return (state_ = !state_); }
// Or use a named accessor or a named mutator or invert the bodies or ...
};
int main()
{
SwitchingBool blinker;
std::cout << std::boolalpha;
for (int i{}; i < 10; ++i)
{
std::cout << "From " << blinker << " to " << blinker() << '\n';
}
}
Upvotes: 0
Reputation: 60208
From c++20, you can write:
for (auto b : std::views::iota(1))
{
std::cout << b % 2 << std::endl;
}
Here's a demo.
Upvotes: 0
Reputation: 73051
I think the way you have it is fine, but another way to do it would be like this:
unsigned int count = 0;
while(true) {
std::cout << ((++count%2) != 0) << std::endl;
}
Upvotes: 1
Reputation: 38341
std::cout << (switch = !switch) << std::endl;
Or
std::cout << !switch << std::endl << switch << std::endl;
Upvotes: 3
Reputation: 881193
If all you want to do is change switch
and output it in one line of code, you can do:
std::cout << (switch = !switch) << std::endl;
But that's almost certainly not going to do anything other than reduce your line count by one, a dubious achievement at best. It'll most likely end up as the same underlying machine code.
Upvotes: 2