1

Ok that title is bad, please feel free to suggest something better, I just don't know what to call it.

Suppose I have an object a, and I want to assign some value to it, check that this value meets some condition, then do something if the condition is met. Here is one way of doing this:

int a = 1234;
if (a > 1)
{
  someFunction(a);
}

But what if I don't need a outside of this test? If I try to do if(int a = 1234 > 1) then I get a = 1 because it solves the right hand side first, and if I put the definition in a bracket I get this:

if ((int a = 1234) > 1) // about 3 different errors
{
  someFunction(a);
}

Obviously this isn't a deal-breaker, but since you can declare objects inside for loops I thought it might be possible to achieve something similar with if conditions?

quant
  • 21,507
  • 32
  • 115
  • 211
  • You can't do this. You can declare one variable, initialize it and have its value checked. For anything else, it needs to go before the `if` statement. – jrok Oct 17 '13 at 10:00
  • and thats why you might get left hand side must be var or expression error – user2408578 Oct 17 '13 at 10:04

2 Answers2

1
(int a = 1234)

This is a statement and has no return value, so you cannot compare it against anything.

This is the reason you are getting errors when trying to compare it to 1 on this line:

if ((int a = 1234) > 1)
Paddyd
  • 1,870
  • 16
  • 26
1

I've done this previously using a custom type that contains a value and the result of a comparison:

struct int_comparison {
    int value;
    bool comparison;
    int_comparison(int value): value(value), comparison() {}
    int_comparison &operator>(int rhs) {
        comparison = value > rhs;
        return *this;
    }
    explicit operator bool() const { return comparison; }
};

if (auto i = int_comparison(1234) > 1) {
    std::cout << i.value << '\n';
}

This is in general fairly hard to follow; better usually to use a nested scope:

{
    int i = 1234;
    if (i > 1) {
         ...
    }
}

Hopefully, a TS after C++14 will allow a further pattern using optional and a lambda:

if (auto i = ([](int i) { return i > 1 ? std::optional<int>{i} : std::nullopt; })(1234)) {
    std::cout << *i << '\n';
}

This uses the operator bool on optional that returns whether it is in the engaged state.

ecatmur
  • 152,476
  • 27
  • 293
  • 366