-2

I googled and found a solution in stackoverflow C++ 11 auto compile time or runtime?. It is an duplicate but not entirely, the answer stated there was compile time. Is it really compile time? Let us consider the below example.

auto give_something(bool mybool)
{
    if (mybool)
        return string("auto");
    return 6.66f;
}

int main()
{
    bool mybool = (rand() % 2) ? true : false;
    auto x = give_something(mybool); // how type of x is deduced?
    return 0;
}

Here the type of x and return type of give_something can't be deduced while compiling (my assumption). It should be deduced only at run time. So auto compile time or run time or both?

Community
  • 1
  • 1
jblixr
  • 1,345
  • 13
  • 34

1 Answers1

4

auto works at compile time.

You are correct that the return type of give_something can't be deduced at compile-time. In such a case, your code will not compile. Clang gives this error message for your example:

main.cpp:8:5: error: 'auto' in return type deduced as 'float' here but deduced 
                      as 'std::__cxx11::basic_string<char>' in earlier return 
                      statement
    return 6.66f;
TartanLlama
  • 63,752
  • 13
  • 157
  • 193