Search code examples
c++cfunctioncastingreturn-type

Query regarding the default return type of a function in c++


A book says:

If return type is not mentioned, it defaults to int.

Just to check this I wrote the following code.

#include <iostream>

print() {
    return 3.3;
}

int main(void) {
    double d = print();
    std::cout << d;

    return 0;
}

As expected I got output 3. There's no problem.

I tried the following code which raised some confusion:

#include <iostream>

print() {
    char x = 97;
    std::cout << x;

    return x;
}

int main(void) {
    char c = print();
    std::cout << c;

    return 0;
}

I was expecting error here but I got output as aa.


I've two doubts here:

  1. If the return type of print function is defaults to int, and as I am returning character variable, why I didn't receive any compilation error?

  2. What exactly got returned by print()? As there is no error, clearly print() has returned 97. But x was storing a. Then how 97 got returned?


Solution

  • [In Visual Studio C++ since VS2005]

    You have to specify the return type otherwise you will get a compilation "error C4430: missing type specifier - int assumed. Note: C++ does not support default-int" ...Other systems generate just a warning.

    But, you ignored 1st issue intentionally. So let's assume print() returns int anyway...

    1. If the return type of print function is defaults to int, and as I am returning character variable, why I didn't receive any compilation error?
    • You can convert a 'char' type simply by assigning to an 'int'
    1. What exactly got returned by print()? As there is no error, clearly print() has returned 97. But x was storing a. Then how 97 got returned?
    • print() returns an integer that is a set of zeros & ones: with the decimal representation of 97 and with the ASCII representation of 'a'. Any variable is just a set of zeros & ones, that can be represented in different formats: decimal, hexadecimal, ASCII characters, etc.

    --

    If you want to see 9797 you have to write:

    #include <iostream>
    
    int print() // 1st issue: Add a return-type
    {
        char x = 97; // The ASCII code of 'a' character
        std::cout << static_cast<int>(x); // 2nd issue: Cast to int, or it will print 'a'
    
        return x; // You can convert a 'char' type simply by assigning to an 'int'
    }
    
    int main()
    {
        char c = static_cast<char>(print());
        std::cout << static_cast<int>(c); // Same 2nd issue
    }
    

    "The C++ compiler treats variables of type char, signed char, and unsigned char as having different types. Variables of type char are promoted to int as if they are type signed char by default, unless the /J compilation option is used. In this case, they are treated as type unsigned char and are promoted to int without sign extension." Microsoft Documentation