asd plougry
asd plougry

Reputation: 143

How to correctly declare/assign values for variables in c++

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

Answers (2)

Miljen Mikic
Miljen Mikic

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

rustyx
rustyx

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

Related Questions