user16078551
user16078551

Reputation:

Cleanest way to avoid writing same condition twice

Lets say I have a loop that inputs a value from user, and if the value is equal to zero, it breaks.

Is there a way to do this without writing the same condition twice?

for example:

int x;

do
{
    std::cin >> x;
    
    if (x)
    {
        //code
    }

} while(x);

What is the cleanest way to do this?

Upvotes: 1

Views: 239

Answers (5)

Florin C.
Florin C.

Reputation: 613

How about:

int x;
while (std::cin >> x, x) {
    std::cout << x*5 << std::endl;
}

No ifs, no breaks, the x is already evaluated to be non-zero by the while condition.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490148

It's probably cleanest to write a little function to read the value, and return a boolean to indicate whether you read a non-zero value, then use that function:

bool read(int &x) { 
    std::cin >> x;
    return std::cin && (x != 0);
}

while (read(x)) {
    // code to process x
}

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234715

The most laconic way (and note how it tests the integrity of the input stream) is

while (int x; std::cin >> x && x){
    // code
}

Another approach, which gives you a bit more scope for introducing code for the fail condition, is

for (;;){ // infinite loop idiom
    int x;
    if (std::cin >> x && x){
        // code
        continue; // i.e. go round again
    }
    // ToDo - code here?
    break;
};

is one way. This is not to everyone's taste although the break; before the end of the loop body gives some comfort that the loop is not really infinite.

It also has the advantage that the scope of x is not leaked to the outer scope.

Upvotes: 1

user1196549
user1196549

Reputation:

Verbatim "a loop that inputs a value from user, and if the value is equal to zero, it breaks."

while (true)
{
  std::cin >> x;
  if (x == 0)
    break;
  ...
}

Upvotes: 0

Lukas-T
Lukas-T

Reputation: 11340

When you write the code exactly as you described it with words it get's simpler:

int x;

while(std::cin >> x) // I have a loop that inputs a value from user, and ...
{
    if(x == 0)       // if the value is equal to zero, ...
    {
        break;       // it breaks.
    }

    // do something with x ...
}

The reason for having std::cin >> x; as condition is to stop reading when invalid input is entered or the stream ends.

Upvotes: 1

Related Questions