简体   繁体   中英

Function return type validation by compiler

I read in Thinking in C++ by Bruce Eckel that when a C++ compiler encounters a function it decorates it's name using it's name and arguments. For a function, int func(char ch); it would decorate it's name as _func_char It doesn't use the return type.

In that case, In the below program how does the compiler complain "invalid conversion from int to const char*" when it has not stored the return type during function name decoration? Can anyone please clarify?

#include <iostream>

using namespace std;

int func()
{
    int i = 5;
    return i;
}

int main()
{
    string str = func();
}

Symbol (not just functions) name mangling comes into play at the linking stage. You're getting a compiler error.

The compiler doesn't see the mangled name. It just sees you have a function called func that returns an int and takes no parameters, and so can tell you your code is illegal.

This is an compilation error.
Compiler checks for the validity of the C++ program as per the C++ Standard specification.

Why does the compiler report an error here?

Because compiler can see that return type of the function is int and it is being used to initialize a variable of the type std::string and there is no valid implicit conversion for it.

Note that the language is designed in such a way it allows the compiler to do these kind of type checking, C++ is a statically typed language .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM