Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I'm reading 'C++ All-in-One for Dummies' by J. P. 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.

like image 561
John Allison Avatar asked Nov 20 '18 11:11

John Allison


People also ask

What happens when variables are not properly initialized?

If you don't initialize an variable that's defined inside a function, the variable value remain undefined. That means the element takes on whatever value previously resided at that location in memory.

What is problem of initialization in C++?

Problem of initialization in C++ These data members have no explicitly defined scope thus they are private by default. The private data members cannot be initialized later using the object of the class. Here, if the data members are initialized using the object of the class, then it will show an error.

What is the value of int if not initialized?

Solution. If a variable is declared but not initialized or uninitialized and if those variables are trying to print, then, it will return 0 or some garbage value.

How do you declare and initialize a variable in C++?

Declaring (Creating) Variablestype variableName = value; Where type is one of C++ types (such as int ), and variableName is the name of the variable (such as x or myName). The equal sign is used to assign values to the variable.


1 Answers

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.

like image 50
songyuanyao Avatar answered Oct 10 '22 23:10

songyuanyao