You had asked:
how to understand the "=int()" in this declaration?
bool myLess(const int& x=int(),const int& y=int());
Your function declaration of course returns a bool, but it accepts two parameters which are both a const reference of an integer type. The =
for each parameter is giving the parameters a default value. The int()
is calling the basic type's default constructor. The default constructor for int
will end up being a prvalue with a value of 0
. This will then cause both x
and y
to be assigned to or initially constructed with a value of 0
. Then whatever is passed into the function as arguments will overwrite this initial value.
You may see function declarations written like this just to ensure that the parameters themselves are always initialized to something specifically 0
. This way if the function is ever called and the references are used after the function call, the next calculation that uses the referenced variables will not use garbage data, especially if the function's internal code has checks for valid data and does something different if the value is 0
. This will ensure that if only 1 parameter was passed, at least the defaulted is constructed to 0
.
It has no different effect than:
bool myLess(const int& x=0, const int& y=0);
When it comes to your used example:
double x1{3.5}, x2{4.5};
bool b = myLess(x1,x2);
When you are passing x1
and x2
into this function, what happens here is the double
type is being casted to an int
type and you will lose data or information due to truncation. Even though x1
has a value of 3.5
and x2
has a value of 4.5
, if your compiler will compile the above code, the values that the function will see are 3
and 4
respectively.