How can I declare and define multiple variables in one line using C++?

后端 未结 10 1642
抹茶落季
抹茶落季 2020-11-27 11:09

I always though that if I declare these three variables that they will all have the value 0

int column, row, index = 0;

Bu

相关标签:
10条回答
  • 2020-11-27 11:40

    When you declare:

    int column, row, index = 0;
    

    Only index is set to zero.

    However you can do the following:

    int column, row, index;
    column = index = row = 0;
    

    But personally I prefer the following which has been pointed out.
    It's a more readable form in my view.

    int column = 0, row = 0, index = 0;
    

    or

    int column = 0;
    int row = 0;
    int index = 0;
    
    0 讨论(0)
  • 2020-11-27 11:40

    When you declare a variable without initializing it, a random number from memory is selected and the variable is initialized to that value.

    0 讨论(0)
  • 2020-11-27 11:45
    int column = 0, row = 0, index = 0;
    
    0 讨论(0)
  • 2020-11-27 11:45

    Possible approaches:

    • Initialize all local variables with zero.
    • Have an array, memset or {0} the array.
    • Make it global or static.
    • Put them in struct, and memset or have a constructor that would initialize them to zero.
    0 讨论(0)
  • 2020-11-27 11:51

    As others have mentioned, from C++17 onwards you can make use of structured bindings for multiple variable assignments.

    Combining this with std::array and template argument deduction we can write a function that assigns a value to an arbitrary number of variables without repeating the type or value.

    #include <iostream>
    #include <array>
    
    template <int N, typename T> auto assign(T value)
    {
        std::array<T, N> out;
        out.fill(value);
        return out;
    }
    
    int main()
    {
        auto [a, b, c] = assign<3>(1);
    
        for (const auto& v : {a, b, c})
        {
            std::cout << v << std::endl;
        }
    
        return 0;
    }
    

    Demo

    0 讨论(0)
  • 2020-11-27 11:54
    int column(0), row(0), index(0);
    

    Note that this form will work with custom types too, especially when their constructors take more than one argument.

    0 讨论(0)
提交回复
热议问题