How can I declare and define multiple variables in one line using C++?
C++C++ Problem Overview
How do I initialise all these variables to zero without declaring each variable on a new line?
int column, row, index = 0;
C++ Solutions
Solution 1 - C++
int column = 0, row = 0, index = 0;
Solution 2 - C++
With the following declaration, only the last variable (index
) is set to 0
:
int column, row, index = 0;
Instead, the following sets all variables to 0
:
int column, row, index;
column = index = row = 0;
But personally, I find the following methods much more readable:
int column = 0, row = 0, index = 0;
int column = 0;
int row = 0;
int index = 0;
Solution 3 - C++
As @Josh said, the correct answer is:
int column = 0,
row = 0,
index = 0;
You'll need to watch out for the same thing with pointers. This:
int* a, b, c;
Is equivalent to:
int *a;
int b;
int c;
Solution 4 - C++
If you declare one variable/object per line not only does it solve this problem, but it makes the code clearer and prevents silly mistakes when declaring pointers.
To directly answer your question though, you have to initialize each variable to 0 explicitly. int a = 0, b = 0, c = 0;
.
Solution 5 - C++
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.
Solution 6 - C++
As of C++17, you can use Structured Bindings:
#include <iostream>
#include <tuple>
int main ()
{
auto [hello, world] = std::make_tuple("Hello ", "world!");
std::cout << hello << world << std::endl;
return 0;
}
Solution 7 - C++
I wouldn't recommend this, but if you're really into it being one line and only writing 0 once, you can also do this:
int row, column, index = row = column = 0;
Solution 8 - C++
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
, andmemset
or have a constructor that would initialize them to zero.
Solution 9 - C++
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;
}
Solution 10 - C++
When you declare a variable without initializing it, a random number from memory is selected and the variable is initialized to that value.