Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto Function with if Statement won't return a value

Tags:

c++

I made a template and an auto function that compare 2 values and return the smallest one. This is my code:

#include <iostream>
using namespace std;

// Template with a value returning function: PrintSmaller
template <typename T, typename U>
auto PrintSmaller(T NumOne, U NumTwo) {
    if (NumOne > NumTwo) {
        return NumTwo;
    }
    else {
        return NumOne;
    }
}

int main() {

    int iA = 345;
    float fB = 23.4243;

    cout << PrintSmaller(iA, fB) << endl;
    cout << PrintSmaller(fB, iA) << endl;

    return 0;
}

But it won't compile, I get this error on VS 2015: Error C3487 'int': all return expressions must deduce to the same type: previously it was 'float'

However, if I delete the if statement and write the function PrintSmaller like this it works with no problems :

auto PrintSmaller(T NumOne, U NumTwo) {
return (NumOne < NumTwo ? NumOne : NumTwo);
}

What is the difference ? and why the first code won't compile ? Thank you.

like image 603
Mike .H Avatar asked Jan 04 '23 19:01

Mike .H


1 Answers

A function can only have a single return type. Using return type deduction means that it will be deduced based on the type of the expression in the first return statement the parser sees. If later return statements do not return expressions of the same type, then the function is considered to be self-contradictory and thus ill-formed.

In the second case, the ?: determines the type of the expression based on a common type determined based on the second and third sub-expressions. The two sub-expressions will be converted to this common type.

That's different from how return type deduction works. If you intend for your first case to work, then you need to explicitly convert the returned value to the desired return type.

like image 85
Nicol Bolas Avatar answered Jan 07 '23 19:01

Nicol Bolas