Search code examples
c++cinitializationdeclarationdefinition

Is there a way to declare multiple objects of the same type at once and initialize them immediately with the same rvalue by just one expression?


I want to declare multiple objects of the same type and initialize them with the same rvalue by just one expression; without the need to declare and initialize them by separate statements.

What I want is something like:

int a = b = 10;  // dummy-statement. This does not work.

or

int a = int b = 10; // dummy-statement. This does not work either.

instead of

int b = 10;
int a = b;

Is there a way to do that?


Solution

  • Technically, yes: int a = value, b = a;, or you might consider int a, b = a = value;. Without repeating identifiers, no, at least not in C; the grammar simply does not provide for it. Each ”declarator = initializer” in the grammar can declare only one object, per grammar production in C 2018 6.7.6 1 and explicit statement in 6.7.6 2: “Each declarator declares one identifier…”

    As mentioned in a comment, here is a horrible way to do it in C++. I make no representations regarding C++’s rules about order of initialization in a single declaration, issues about threading, and so on. This is presented as an educational exercise only. Never use this in production code.

    template<class T> class Sticky
    {
    private:
        static T LastInitializer;   //  To remember last explicit initializer.
        T Value;                    //  Actual value of this object.
    
    public:
        //  Construct from explicit initializer.
        Sticky<T>(T InitialValue) : Value(InitialValue)
            { LastInitializer = InitialValue; }
    
        //  Construct without initializer.
        Sticky<T>() : Value(LastInitializer) {}
    
        //  Act as a T by returning const and non-const references to the value.
        operator const T &() const { return this->Value; }
        operator T &() { return this->Value; }
    };
    
    template<class T> T Sticky<T>::LastInitializer;
    
    #include <iostream>
    
    int main(void)
    {
        Sticky<int> a = 3, b, c = 15, d;
    
        std::cout << "a = " << a << ".\n";
        std::cout << "b = " << b << ".\n";
        std::cout << "c = " << c << ".\n";
        std::cout << "d = " << d << ".\n";
        b = 4;
        std::cout << "b = " << b << ".\n";
        std::cout << "a = " << a << ".\n";
    }
    

    Output:

    a = 3.
    b = 3.
    c = 15.
    d = 15.
    b = 4.
    a = 3.