Search code examples
c++c++17coding-style

How can I make quick expression that's visible to assign to const?


I want to assign some value to a const, where it used to be something like

const int x = animal == "cat" ? 0 : 1;

But now, I want to make it so that if animal == cat, assign 0, and if dog returns 1, else 2 to the const. Well, in reality, it's not that simple but say something like use equation a, in this case, equation b, and equation c in this case.

Of course, I can always do something like

const int x = FunctionToHandleIt();

But the logic is so simple. I think it's much cleaner for the code to write out the expression right there so people can look at it and know exactly what's happening right then and there instead of going through the header and definition of the function to see what's happening.

What is the better way to handle a case like this to assign something to const that's more than a few lines? But, not worth making a whole function for it?


Solution

  • With the help of a lambda function, there is no need to specify the definition of another function somewhere in the code.

    const string animal = "dog";
    
    const int x = [animal]() {
        if (animal == "cat")
            return 0;
        else if (animal == "dog")
            return 1;
        else
            return 2;
    }();
    
    cout << x << endl;
    

    The variable animal is captured to be validated in the inner code block. The respective values are returned after that.