Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does int() do in C++?

Tags:

The following code can pass compiling and will print 0 on the console. I saw similar code in STL. Does type int in C++ have a constructor? Is int() a call of some defined function?

int main() {     int a = int();     cout << a << endl;     return 0; } 
like image 464
coinsyx Avatar asked Jun 16 '13 09:06

coinsyx


People also ask

What does int function do in C?

int() is the constructor of class int . It will initialise your variable a to the default value of an integer, i.e. 0 . Even if you don't call the constructor explicitly, the default constructor, i.e. int() , is implicitly called to initialise the variable.

What does int () mean in C ++?

An int variable contains only whole numbers Int, short for "integer," is a fundamental variable type built into the compiler and used to define numeric variables holding whole numbers. Other data types include float and double. C, C++, C# and many other programming languages recognize int as a data type.

What is the meaning of int ()?

What Does Integer (INT) Mean? An integer, in the context of computer programming, is a data type used to represent real numbers that do not have fractional values. Different types of integer data types are stored on machines in different ways.

What does int * mean in C?

int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer. Since the sizeof operator returns the size of the datatype or the parameter we pass to it.


1 Answers

In this context,

int a = int(); // 1) 

it value-initializes a, so that it holds value 0. This syntax does not require the presence of a constructor for built-in types such as int.

Note that this form is necessary because the following is parsed as a function declaration, rather than an initialization:

int a(); // 2) function a() returns an int 

In C++11 you can achieve value initialization with a more intuitive syntax:

int a{}; // 3) 

Edit in this particular case, there is little benefit from using 1) or 3) over

int a = 0; 

but consider

template <typename T> void reset(T& in) { in = T(); } 

then

int i = 42; reset(i);   // i = int() 
like image 106
juanchopanza Avatar answered Oct 20 '22 17:10

juanchopanza