Reputation: 143
Should I declare variables at the top of my c++ program before assigning values:
int i;
std::string x;
std::string retval;
x = "foo";
i = 5;
retval = somefunction();
Or alternatively is it correct/acceptable to assign values to variables the following way:
int i = 5;
std::string x = "foo";
std::string retval = somefunction();
I am new to c++ and I would like to know which way is accepted by the c++ community.
Upvotes: 1
Views: 2078
Reputation: 15241
When you know the initial value beforehand, the second way is more efficient because you only invoke a constructor, while in the first you first invoke default constructor and then an assignment operator.
Upvotes: 4
Reputation: 85256
Second way is more idiomatic C++ and should be preferred. See also core guideline NR.1:
Reason
The “all declarations on top” rule is a legacy of old programming languages that didn’t allow initialization of variables and constants after a statement. This leads to longer programs and more errors caused by uninitialized and wrongly initialized variables.
It is also more efficient because the first is a default-construction followed by assignment, and the second one is simply construction.
Upvotes: 6