简体   繁体   中英

int x; int y; int *ptr; is not initialization, right?

I'm reading 'C++ All-in-One for Dummies' by JP Mueller and J. Cogswell and stumbled onto this:

#include <iostream>
using namespace std;
int main()
{
    int ExpensiveComputer;
    int CheapComputer;
    int *ptrToComp;
...

This code starts out by initializing all the goodies involved — two integers and a pointer to an integer.

Just to confirm, this is a mistake and should read '... by declaring', right? It's just strange to me that such basic mistakes still make their way to books.

From the point of view of the language, this is default initialization . The problem is, they are initialized to indeterminate values.

otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.

Default initialization of non-class variables with automatic and dynamic storage duration produces objects with indeterminate values (static and thread-local objects get zero initialized)

Note that any attempt to read these indeterminate values leads to UB .

From the standard, [dcl.init]/7

To default-initialize an object of type T means:

  • If T is a (possibly cv-qualified) class type ([class]), constructors are considered. The applicable constructors are enumerated ([over.match.ctor]), and the best one for the initializer () is chosen through overload resolution ([over.match]). The constructor thus selected is called, with an empty argument list, to initialize the object.

  • If T is an array type, each element is default-initialized.

  • Otherwise, no initialization is performed.

Yes you are correct.

You declared and defined these variables, you did not initialize them!

PS: What is the difference between a definition and a declaration?

This code both declares and defines three variables but does not initialize them (their values are said to be indeterminate ).

A variable declaration only must include keyword extern .

Right. Hence, "dummies". :)

We can't even blame this on legacy; historically C programmers would declare* a variable and then "initialize" it later with its first assignment.

But it was never the case that simply declaring a variable, without an initializer, were deemed to be "initializing" it.**

So the wording is just wrong.

* Technically we're talking about definitions , but when we say "declare a variable" we almost always mean defining declarations.

** Though objects with static storage duration do undergo their own zero-initialisation phase before anything else happens, so forgoing initialisation yourself is not a catastrophe in that case. Still, we cannot claim that we have initialised that object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM