Drahsid
Drahsid

Reputation: 21

conditional in value assignment

In c++, I want to use conditionals when assigning values, for example:

int i = true && 5 || 3;

For example, using Lua you can write this:

i = true and 5 or 3

I am not sure that this is possible

Here is something that I tried:

#include "stdafx.h"
#include <iostream>

void main()
{
    int test = (true && 5) || 1;
    int test2 = (false && 6) || 2;

    std::cout << "Test: " << test << std::endl << "Test2: " << test2 << std::endl;
    for(;;);
}

Upvotes: 1

Views: 215

Answers (4)

Richard Hodges
Richard Hodges

Reputation: 69912

If we really wanted to, as of c++11 (which gives us the and and or keywords as a synonyms for && and ||), we could almost strong-arm the c++ compiler into compliance, and get it to compile this:

int x = when_true(b) and 5 or 6;

In order to do this we would need to provide some scaffolding:

#include <iostream>

struct maybe_int {
    bool cond;
    int x;

    operator int() const { return x; }
};

int operator || (const maybe_int& l, int r) {
    if (l.cond) return l.x;
    return r;
}

struct when_true {
    when_true(bool condition)
    : _cond(condition)
    {}

    auto operator&&(int x) const {
        return maybe_int { _cond, x };
    }

    bool _cond;

};


int main()
{
    using namespace std;

    auto b = false;
    int x = when_true(b) and 5 or 6;
    cout << x << endl;
    return 0;
}

My suggestion would be that you don't try this kind of thing at work.

Upvotes: 0

DimChtz
DimChtz

Reputation: 4343

What you need is a conditional expression:

  int i = true ? 2 : 5;

In this case i will be 2.

Upvotes: 1

Nicol Bolas
Nicol Bolas

Reputation: 474366

C++ isn't Lua.

In Lua, true and 5 expression results in 5. That's simply how Lua works with boolean expressions.

And that's not how C++ works with boolean expressions. In C++, a boolean expression results in a boolean value. That is, either true or false.

If you want to select between two values based on a condition, we have an operator for that:

int i = true ? 5 : 3;

If the condition is true, you get the value before the :. If it's false, you get the value after the :.

Upvotes: 3

MSalters
MSalters

Reputation: 180245

I suspect you're looking for int test = true ? 5 : 1;

Upvotes: 1

Related Questions