-1
#include <iostream>  // std::cout

template <class T>
T Sum(T x, T y) {
  return x + y;
}
int main() {
  std::cout << Sum<int>(5, 10);
  std::cout << "\n" << 'a' + 'b';
  std::cout << "\n" << Sum<char>('a', 'b');
  return 0;
}

The program freezes on the last line when using cpp.sh site, can somebody please explain why?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
DoehJohn
  • 201
  • 1
  • 8

3 Answers3

2

Assuming signed 8 bit char, which is very common, adding 'a' and 'b' and storing the result in a char overflows and causes undefined behavior. Thus, the program is free to do anything. In my testing with GCC it prints some garbage and main exits with 0.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
0

As @Ayxan already pointed out, adding two chars and storing the result in a char is not a good idea, you can change the return type of your function to auto as the operationchar + char returns int (see this answer). Simply write

template <class T> auto Sum(T x, T y)
{
    std::cout << sizeof(x) << " " << sizeof(y) << " " << sizeof(x+y) << std::endl;;
    return x + y;
}

Running your main will output:

4 4 4
15
195
1 1 4
195

See the live demo.

StefanKssmr
  • 1,196
  • 9
  • 16
  • he written that application hangs on last line. So this is not the problem. – Marek R May 22 '20 at 11:24
  • @MarekR You're right, I haven't read carefully enough that he was only looking for an explanation and not a fix. I'll still leave this here, maybe it helps someone else. – StefanKssmr May 22 '20 at 11:37
0

Problem is site you used for testing. As I showed in comment your code doesn't hangs on:

Problem is on site cpp.sh site.

Most probably this site is configured to assume UTF-8 encoding in application output. Now when you do addition of char characters are promoted to int that is why 195 is printed in earlier line. Your Sum clips this results to char type (here is undefined behavior since there is integer overflow).

Now in UTF-8 this byte 195 represents is an indicator that current character is build from two bytes. Your program never sends next byte. This site should be able to handle malformed UTF-8 and noticed that stream has ended and not wait for next character. It waits for this character and as a result it hangs. So this is a bug of site cpp.sh.

Marek R
  • 32,568
  • 6
  • 55
  • 140