1
votes

I'm really new to c++ and have just been experimenting around with some code and there's something I don't really seem to get:

 #include<iostream>
 using namespace std;

int f (const long& i) {
    return i+1;
}

void g (long& i) {
    f (i);
}

int main () {
    long la = 0;
    int a = 0;

    int b = f (a);
    long c = f (7);
    la = f (la); 
    cout << "la = " << la << " a = " << a << endl;
    cout << "b = " << b << " c = " << c << endl;
}

So what I don't get: Why does function f accept variables of the type int? a is obviously not a long, but it still accepts it. I don't understand that. Also, since the return type of f is int, does it automatically cast the return result from long to int? I don't really understand what's going on here.

2
The return type has nothing to do with the parameter type. - Ron

2 Answers

1
votes

There is used the so-called usual arithmetic conversions for the argument. An object of the type int is implicitly converted to the type long because the type long has a greater rank than the rank of the type int. That is an object of the type long can accomodate any value of the type int.

As for the return type then there can be obtained an invalid result becuase it is not necessary that an object of the type int can accomodate a value of the type long.

Take into account that if you do not want that the function would accept an object of the type int as an argument you could define the corresponding function with the argument of the type int as deleted.

For example

#include <iostream>

int f (const long& i) {
    return i+1;
}

int f( const int & ) = delete;

int main() 
{
    int a = 0;

    f( a );

    return 0;
}

The program does not compile because the function with the parameter of the type int is defined as deleted.

1
votes

C++ allows implicit conversions between certain types. All numerical built-in types are convertible to each other, so the compiler is free to do any conversion between int/long/short/long long and their unsigned equivalents. For more information on type conversions see cppreference