+ 2
Bool Template
Why does this code output 1 and not 2? I get that it is adding booleans, but could someone explain the logic? #include <iostream> using namespace std; template <class T> T sum(T a, T b) { return a+b; } int main () { bool x=true; bool y=true; cout << x << endl; cout << y << endl; cout << sum(x, y) << endl; } https://code.sololearn.com/chzqe7tVGg61/#cpp
5 odpowiedzi
+ 2
You're performing arithmetic addition on booleans and the return type is also boolean. The behavior:
#include<iostream>
bool f(bool a,bool b){
return a+b;
}
int main() {
bool a{true};
bool b{true};
auto c=a+b;
std::cout<<typeid(a).name()<<std::endl;//bool
std::cout<<typeid(b).name()<<std::endl;//bool
std::cout<<typeid(c).name()<<std::endl;//int
std::cout<<typeid(f(a,b)).name()<<std::endl;//int
return 0;
}
Explanation: bool+bool gets promoted to int, then gets demoted to bool on the function return
+ 2
I don't know c++ but I checked for a little and even when you will return with actual numbers like 3 + 5 the returned value will be 1 so I think it's a problem of the return type so change the return type to int and it will work fine
+ 2
Edward Finkelstein The template parameter T is deduced to bool(I guess that you already knew that)
Addition of two bools causes the bools to be promoted to int first.
But since your return type is T(which becomes bool in your case),the result of the addition is converted to either a true or false(1 or 0) depending on the result of the addition
To get 2 as the answer,just change the return type from T to auto.
+ 1
Thank you all.
+ 1
Ockert van Schalkwyk
The last std::cout line in your code outputs b, doesn't that mean bool?