1

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.

asd plougry
  • 143
  • 1
  • 9
  • Both will work. The latter is better style because it's clear at a glance that the variables are initialized. – interjay Jan 05 '20 at 14:31
  • Either is fine, though the second is probably better when possible because it guarantees a value in each variable and avoids any [undefined behavior](https://stackoverflow.com/questions/32132574/does-undefined-behavior-really-permit-anything-to-happen) from reading an uninitialized variable. –  Jan 05 '20 at 14:32
  • 4
    They're not equivalent operations. One is initialization, the other assignment. The use case for each is obvious. Use initialization via construction (the second snippet) when initial values are known at variable declaration time; use assignment (the first snippet) when that is not the case. That's seriously it. – WhozCraig Jan 05 '20 at 14:32
  • you question is in C++, it's not C at all. There is no thing like C/C++ – Van Tr Jan 05 '20 at 14:41
  • The answers are really good. I suggest you check this out 'rules of three in C++' because you're new. That way you can understand better. – shalom Jan 05 '20 at 14:44

2 Answers2

6

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.

Community
  • 1
  • 1
rustyx
  • 80,671
  • 25
  • 200
  • 267
4

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.

Miljen Mikic
  • 14,765
  • 8
  • 58
  • 66