int a = 0 and int a(0) differences [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a difference in C++ between copy initialization and direct initialization?
I just started to learn C++.
To initialize a variable with a value, I came across
int a = 0;
and
int a(0);
This confuses me a lot. May I know which is the best way?

int a = 0; and int a(0); make no difference in the machine generated code. They are the same.
Following is the assembly code generated in Visual Studio
int a = 10; // mov dword ptr [a],0Ah
int b(10); // mov dword ptr [b],0Ah

They're both the same, so there really is no one "best way".
I personally use
int a = 0;
because I find it more clear and it's more widely used in practice.
This applies to your code, where the type is int. For class-types, the first is copy-initialization, whereas the other is direct-initialization, so in that case it would make a difference.

There's no "best" way. For scalar types (like int in your example) both forms have exactly the same effect.
The int a(0) syntax for non-class types was introduced to support uniform direct-initialization syntax for class and non-class types, which is very useful in type-independent (template) code.
In non-template code the int a(0) is not needed. It is completely up to you whether you want to use the int a(0) syntax, or prefer to stick to more traditional int a = 0 syntax. Both do the same thing. The latter is more readable, in my opinion.

From a practical point of view: I would only use int a = 0;.
The int a(0) may be allowed but never used in practice in itself.
I think it should not bother you on your level, but let us go further.
Let's say that a is a class, not an int.
class Demo{
public:
Demo(){};
Demo(int){};
};
Demo a;
Demo b(a);
Demo c = a; // clearly expressing copy-init
In this example both b(a) and c=a do the same, and I would discourage you using the fist solution. My reason is, that is looks similar to c(2) which is a construction from arguments.
There are only two valid uses of this bracket-style initialization:
initialization lists (Demo(int i):data(i){} if Demo has an int data member data),
new's: Demo *p=new Demo(a); // copy constructing a pointer

It’s that simple. (Well, almost — there are a few things you can’t name your variables, which we’ll talk about in the next section)
You can also assign values to your variables upon declaration. When we assign values to a variable using the assignment operator (equals sign), it’s called an explicit assignment:
int a= 5; // explicit assignment
You can also assign values to variables using an implicit assignment:
int a(5); // implicit assignment
Even though implicit assignments look a lot like function calls, the compiler keeps track of which names are variables and which are functions so that they can be resolved properly.

In textbooks and literature, one is direct initialization and the other is copy initialization. But, in terms of machine code, there is no difference.

The difference is that () initialization is when you explicitly want it to take one parameter only, e.g:
You can:
int a = 44 + 2;
but you can't:
int a(44) + 2;

Related

What is the difference bettwen using "()" and "{}" to initialize a variable? [duplicate]

The C++ reference pages say that () is for value initialisation, {} is for value and aggregate and list initialisation. So, if I just want value initialisation, which one do I use? () or {}? I'm asking because in the book "A Tour of C++" by Bjarne himself, he seems to prefer using {}, even for value initialisation (see for example pages 6 and 7), and so I thought it was good practice to always use {}, even for value initialisation. However, I've been badly bitten by the following bug recently. Consider the following code.
auto p = std::make_shared<int>(3);
auto q{ p };
auto r(p);
Now according to the compiler (Visual Studio 2013), q has type std::initializer_list<std::shared_ptr<int>>, which is not what I intended. What I actually intended for q is actually what r is, which is std::shared_ptr<int>. So in this case, I should not use {} for value initialisation, but use (). Given this, why does Bjarne in his book still seem to prefer to use {} for value initialisation? For example, he uses double d2{2.3} at the bottom of page 6.
To definitively answer my questions, when should I use () and when should I use {}? And is it a matter of syntax correctness or a matter of good programming practice?
Oh and uh, plain English if possible please.
EDIT:
It seems that I've slightly misunderstood value initialisation (see answers below). However the questions above still stands by and large.
Scott Meyers has a fair amount to say about the difference between the two methods of initialization in his book Effective Modern C++.
He summarizes both approaches like this:
Most developers end up choosing one kind of delimiter as a default, using
the other only when they have to. Braces-by-default folks are
attracted by their unrivaled breadth of applicability, their
prohibition of narrowing conversions, and their immunity to C++’s most
vexing parse. Such folks understand that in some cases (e.g., creation
of a std::vector with a given size and initial element value),
parentheses are required. On the other hand, the go-parentheses-go
crowd embraces parentheses as their default argument delimiter.
They’re attracted to its consistency with the C++98 syntactic
tradition, its avoidance of the auto-deduced-a-std::initializer_list
problem, and the knowledge that their object creation calls won’t be
inadvertently waylaid by std::initializer_list constructors. They
concede that sometimes only braces will do (e.g., when creating a
container with particular values). There’s no consensus that either
approach is better than the other, so my advice is to pick one and
apply it consistently.
This is my opinion.
When using auto as type specifier, it's cleaner to use:
auto q = p; // Type of q is same as type of p
auto r = {p}; // Type of r is std::initializer_list<...>
When using explicit type specifier, it's better to use {} instead of ().
int a{}; // Value initialized to 0
int b(); // Declares a function (the most vexing parse)
One could use
int a = 0; // Value initialized to 0
However, the form
int a{};
can be used to value initialize objects of user defined types too. E.g.
struct Foo
{
int a;
double b;
};
Foo f1 = 0; // Not allowed.
Foo f1{}; // Zero initialized.
First off, there seems to a terminology mixup. What you have is not value initialisation. Value initialisation happens when you do not provide any explicit initialisation arguments. int x; uses default initialisation, the value of x will be unspecified. int x{}; uses value initialisation, x will be 0. int x(); declares a function—that's why {} is preferred for value initialisation.
The code you've shown does not use value initialisation. With auto, the safest thing is to use copy initialisation:
auto q = p;
There is another important difference: The brace initializer requires that the given type can actually hold the given value. In other words, it forbids narrowing of the value, like rounding or truncation.
int a(2.3); // ok? a will hold the value 2, no error, maybe compiler warning
uint8_t c(256); // ok? the compiler should warn about something fishy going on
As compared to the brace initialization
int A{2.3}; // compiler error, because int can NOT hold a floating point value
double B{2.3}; // ok, double can hold this value
uint8_t C{256}; // compiler error, because 8bit is not wide enough for this number
Especially in generic programming with templates you should therefore use brace initialization to avoid nasty surprises when the underlying type does something unexpected to your input values.
{} is value initialization if empty, if not it is list/aggregate initialization.
From the draft, 7.1.6.4 auto specifier, 7/... Example,
auto x1 = { 1, 2 }; // decltype(x1) is std::initializer_list<int>
Rules are a little bit complex to explain here (even hard to read from the source!).
Herb Sutter seems to be making an argument in CppCon 2014 (39:25 into the talk) for using auto and brace initializers, like so:
auto x = MyType { initializers };
whenever you want to coerce the type, for left-to-right consistency in definitions:
Type-deduced: auto x = getSomething()
Type-coerced: auto x = MyType { blah }
User-defined literals auto x = "Hello, world."s
Function declaration: auto f { some; commands; } -> MyType
Named Lambda: using auto f = [=]( { some; commands; } -> MyType
C++11-style typedef: using AnotherType = SomeTemplate<MyTemplateArg>
Scott Mayers just posted a relevant blog entry Thoughts on the Vagaries of C++ Initialization. It seems that C++ still has a way to go before achieving a truly uniform initialization syntax.

C++ differences between () and {}

I am learning C++.
I've seen some people doing this:
int a = 2;
But also:
int b(2);
And also:
int c{2};
What am I supposed to use?
What are the differences between those?
Thanks,
Do'
What am I supposed to use ?
You can use any of them.
What are the differences between those ?
int a = 2; // A
int b(2); // B
int c{2}; // C
A is copy initialisation. B and C are direct initialisation.
C uses a braced-init-list and is therefore direct list initialisation. A and B allow initialising with a narrowing conversion while list initialisation allows only non-narrowing conversion. This is sometimes advantageous, since it can help detect unintentional narrowing which is a source of bugs. In this particular case however, it is safe to assume that 2 is appropriate value for int.

why two ways to variable initialization [duplicate]

This question already has answers here:
Is there a difference between copy initialization and direct initialization?
(9 answers)
Closed 7 years ago.
Why C++ gives two ways to initialize variable?
First way is C-type initialization where we assign value to the variable at the place where we define it.
int a = 0;
Another way, constructor initialization which is done by enclosing the initial value between parentheses ().
int a(0);
My question is what was reason that the creators of C++ were forced to introduce new way to initialize variable. Although C-style initialization was doing the job.
int a = 0; exists for legacy (and because it feels natural, especially for built-in types), and int a(0) exists for explicitness and consistency - there are situations where you may want a more complicated copy constructor which takes multiple arguments or arguments of other types (conversion constructors).
If it can (ie. if the appropriate constructor is available), the compiler will treat both int a = 0; and int a(0) as a call to the copy constructor. The precise behavior is explained here.
I think this is because constructors with initializer lists are generally faster, which I think has to do with the the fact that the value can be placed into the newly allocated variable memory in fewer memory accessing operations. Here is a CPP FAQ on that topic (a great website for questions like this, btw).
Basically implicit is the preferred way:
int nValue = 5; // explicit initialization
int nValue(5); // implicit initialization
Here are some reads:
http://www.learncpp.com/cpp-tutorial/21-basic-addressing-and-variable-declaration/
Explicit Assignment vs Implicit Assignment
When you use the first, what you call C-type initialization, the variable will be written to twice, first the default value and second the assignment, as for the second case it will directly be set to the specified value. I think modern compilers optimize this for primitive types but for objects it could make quite a difference.

Which declaration is the standard in C++/C?

Which of the following declaration is the standard and preferred?
int x = 7;
or
int x(7);
int x(7);
is not the valid way of declaring & initializing a variable in C;
I suggest you to get a good book for learning C and use a good compiler.
in c kind of langueges you normally use
int x = 7;
You've tagged this question as both C and C++, but the answers aren't really the same for the two.
In C, int x(7); simply doesn't work. It won't even compile. Since this form doesn't work at all in C, the preferred form is int x = 7;.
In C++, int x(7); works -- but you have to be careful, as this form can lead to the "most vexing parse"; if whatever was in the parentheses could be interpreted as a type instead of a value, this would be parsed as declaring a function named x that returned an int instead of defining an int with the value specified in the parentheses. Likewise, if you leave the parens empty: int x(); you end up with a function declaration.
C++ does have another form: int x{7};. Some call this "universal initialization". It does remove any ambiguity -- anything like T id { x }; where T is a type must be a definition of a id with x as an initializer. Some people dislike this, however, because it introduces somewhat different semantics -- for example, "narrowing" conversions are prohibited in this case, so you can't blindly change existing code to use the new form. For example:
int x(12.34); // no problem
int y{ 12.34 }; // won't compile -- double -> int is a narrowing conversion
This isn't particularly likely to happen with a literal as I've shown above, but something like:
void f(double x) {
int y(x);
// ...
...is rather more likely -- and still isn't allowed.
Unfortunately, going "back" to the C-style initialization doesn't cure all the possible problems either. At least in theory, it does copy initialization instead of direct initialization, so the type you're initializing must have a copy constructor available to do this initialization. For example:
class T {
T(T const &) = delete;
public:
T(int) {}
};
int main() {
T t = 1;
}
This isn't officially allowed to work, because what it's supposed to do is use T(int) to create a temporary T object, then use T(T const &) to copy-construct t from that temporary. Since we've deleted the copy constructor, it can't (officially) be used. This can be particularly confusing, because nearly all compilers will normally do the job without using the copy constructor at all, so the code will normally compile and work just fine--but the minute you turn on the mode where the compiler tries to follow the standard as closely as possible, the code won't compile at all.
Some people find the changes in "uniform initialization" so off-putting that they recommend against using it at all. Personally, I prefer to use it and simply ensure that I'm not doing any narrowing conversions (or use an explicit cast if a narrowing conversion just can't be avoided).
In general
int x = 7;
is the standard way, and the ONLY way in C.
However, in C++, you can initialize an int using x(7) in cases such as constructor initializer lists, where you have to invoke a 'constructor' for each variable you are initializing that way. For primitives, you do this with the x(7) syntax.

Is initializing a garbage variable truly initializing or just an assignment?

I generally see examples of initialisation vs assignment like this:
int funct1(void)
{int a = 5; /*initialization*/
a = 6;} /*assignment*/
Obviously something left as garbage or undefined somehow is uninitialized.
But could some one please define if initialization is reserved for definition statements and/or whether assignments can be called initialisation?
int funct2(void)
{int b;
b = 5;} /*assignment, initialization or both??*/
Is there much of a technical reason why we can't say int b is initialised to garbage (from the compilers point of view)?
Also if possible could this be compared with initializing and assinging on non-primitive data types.
I'll resurrect this thread to add an important point of view, since the puzzlement about terminology by the OP is understandable. As #OliCharlesworth pointed out (and he's perfectly right about that) as far as the C language standard is concerned initialization and assignment are two completely different things. For example (assuming local scope):
int n = 1; // definition, declaration and **initialization**
int k; // just definition + declaration, but no initialization
n = 12; // assignment of a previously initialized variable
k = 42; // assignment of a previously UNinitialized variable
The problem is that many books that teach programming aren't so picky about terminology, so they call "initialization" any "operation" that gives a variable its first meaningful value. So, in the example above, n = 12 wouldn't be an initialization, whereas k = 42 would. Of course this terminology is vague, imprecise and may be misleading (although it is used too often, especially by teachers when introducing programming to newbies). As a simple example of such an ambiguity let's recast the previous example taking global scope into account:
// global scope
int n = 1; // definition, declaration and **initialization**
int k; // definition, declaration and **implicit initialization to 0**
int main(void)
{
n = 12; // assignment of a previously initialized variable
k = 42; // assignment of a previously initialized variable
// ... other code ...
}
What would you say about the assignments in main? The first is clearly only an assignment, but is it the second an initialization, according to the vague, generic terminology? Is the default value 0 given to k its first "meaningful" value or not?
Moreover a variable is commonly said to be uninitialized if no initialization or assignment has been applied to it. Given:
int x;
x = 42;
one would commonly say that x is uninitialized before the assignment, but not after it. The terms assignment and initializer are defined syntactically, but terms like "initialization" and "uninitialized" are often used to refer to the semantics (in somewhat informal usage). [Thanks to Keith Thompson for this last paragraph].
I dislike this vague terminology, but one should be aware that it is used and, alas, not too rare.
As far as the language standard is concerned, only statements of the form int a = 5; are initialisation. Everything of the form b = 5; is an assignment.
The same is true of non-primitive types.
And to "Is there much of a technical reason why we can't say int b is initialised to garbage", well, if you don't put any value into a memory location, it's not "initialisation". From the compiler's point of view, no machine language instruction is generated to write to the location, so nothing happens.