Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning values to multiple declarations on same line

Tags:

c++

I am creating variables as such

std::string str1,str2,str3,str4 = "Default";

however the variables do not have the Default value. How can I assign values to variables created this way

like image 567
MistyD Avatar asked Sep 10 '13 23:09

MistyD


2 Answers

str4 will have the value you're looking for. You just didn't initialize the others. Use:

std::string str1 = "Default", str2 = "Default", str3 = "Default", str4 = "Default";

Or, probably better:

std::string str1 = "Default";
std::string str2 = "Default";
std::string str3 = "Default";
std::string str4 = "Default";

If you're concerned about doing so much typing, you can use assignment instead of initialization:

std::string str1, str2, str3, str4;
str1 = str2 = str3 = str4 = "Default";

But that's got different semantics and is (IMHO) a bit hinky.

like image 140
Carl Norum Avatar answered Sep 23 '22 06:09

Carl Norum


Generally when you have variable names with numbers in them, an array will be better suited. This gives you the added benefit of using std::fill_n as well

#include <algorithm>

std::string str[4];
std::fill_n( str, 4, "Default" ); // from link provided by Smac89
// str[0], str[1], str[2], str[3] all set to "Default"
like image 22
clcto Avatar answered Sep 20 '22 06:09

clcto