pythonc++c++11arduinopython-3.8

Equivalent of python walrus operator (:=) in c++11?


Recently I have been using the := operator in python quite a bit, in this way:

if my_object := SomeClass.function_that_returns_object():
    # do something with this object if it exists
    print(my_object.some_attribute)

The question

Is there any way to do this in c++11 without the use of stdlib? for example in an arduino sketch if I wanted to use a method that may potentially return zero, such as:

if(char * data = myFile.readBytes(data, dataLen))
{
    // do something
}
else
{
    // do something else
}

Solution

  • Python's := assignment expression operator (aka, the "walrus" operator) returns the value of an assignment.

    C++'s = assignment operator (both copy assignment and move assignment, as well as other assignment operators) does essentially the same thing, but in a different way. The result of an assignment is a reference to the object that was assigned to, allowing that object to be evaluated in further expressions.

    So, the equivalent of:

    if my_object := SomeClass.function_that_returns_object():
        # do something with this object if it exists
        print(my_object.some_attribute)
    

    Would be just like you showed:

    SomeType *my_object;
    if ((my_object = SomeClass.function_that_returns_object())) {
        // do something with this object if it exists
        print(my_object->some_attribute);
    }
    

    If function_that_returns_object() returns a null pointer, the if evaluates my_object as false, otherwise it evaluates as true. The same can be done with other types, eg:

    int value;
    if ((value = SomeClass.function_that_returns_int()) == 12345) {
        // do something with this value if it matches
    }