hornymoose
hornymoose

Reputation: 21

Advantages to different ways of declaring a variable in c++ when using .size()?

Consider the code below:

//ask for user's name
cout << "What is your FIRST name?\n\n";

//read the user's name
string name; //define name
cin >> name; //read into name

//build the message we want to write
const string greeting = "Hello, " + name + "!";

Suppose I want to know the number of characters in the string variable greeting. A simple way to do this is with .size(). Suppose I want to call the resulting value greetingLength

Is there any benefit to writing

const int greetingLength(greeting.size());

instead of

const int greetingLength=greeting.size();

This question probably has a very obvious question, but I'm a total noob to c++. I've been using MATLAB for over a decade, so the second option looks much better to me, but many tutorials seem to have preference for the first option.

Upvotes: 0

Views: 62

Answers (2)

cigien
cigien

Reputation: 60227

This form:

const int greetingLength(greeting.size());

is direct-initialization

initialization with a nonempty parenthesized list of expressions or braced-init-lists

and the effect is:

Otherwise, standard conversions are used, if necessary, to convert the value of other to the cv-unqualified version of T, and the initial value of the object being initialized is the (possibly converted) value.


This form:

const int greetingLength=greeting.size();

is copy-initialization:

when a named variable (automatic, static, or thread-local) of a non-reference type T is declared with the initializer consisting of an equals sign followed by an expression.

and the effect is:

Otherwise (if neither T nor the type of other are class types), standard conversions are used, if necessary, to convert the value of other to the cv-unqualified version of T.


So both forms have the effect of using standard conversions to convert greeting.size() to an int and initializing greetingLength, and are equivalent.

Upvotes: 2

Syed Mishar Newaz
Syed Mishar Newaz

Reputation: 567

As mentioned in the link:

  int a=5;               // initial value: 5
  int b(3);              // initial value: 3
  int c{2};              // initial value: 2

All of these statements are valid and equivalent. ref: http://www.cplusplus.com/doc/tutorial/variables/

Upvotes: 1

Related Questions