fork download
  1. #include <iostream>
  2. #include <exception>
  3. #include <stdexcept>
  4.  
  5. int gcd(int a, int b) {
  6. // Trigger to fail the test case
  7. if(a<0 /* || b<0 */ ) {
  8. throw std::invalid_argument("a and b must be negative values");
  9. }
  10. if(!(a >= 0 && b >= 0)) {
  11. return -1;
  12. }
  13. if(a==0 || b==0 )
  14. return a+b;
  15. while(a!=b) {
  16. if(a>b) {
  17. a = a - b;
  18. }
  19. else {
  20. b = b - a;
  21. }
  22. }
  23. return a;
  24. }
  25.  
  26. #define expect_true(arg) \
  27.   do { \
  28.   if(!(arg)) { \
  29.   std::cout << "Unexpected false at " \
  30.   << __FILE__ << ", " << __LINE__ << ", " << __func__ << ": " << #arg \
  31.   << std::endl; } \
  32.   } while(false);
  33.  
  34. void test_gcd() {
  35. expect_true(gcd(16,24) == 8);
  36. expect_true(gcd(0, 19) == 19);
  37. bool exceptionCaught = false;
  38. try {
  39. gcd(5, -15);
  40. } catch (const std::invalid_argument& ex) {
  41. std::cout << "Illegal as expected" << std::endl;
  42. exceptionCaught = true;
  43. }
  44. expect_true(exceptionCaught);
  45. }
  46.  
  47. int main() {
  48. test_gcd();
  49. return 0;
  50. }
Success #stdin #stdout 0s 3100KB
stdin
Standard input is empty
stdout
Unexpected false at prog.cpp, 44, test_gcd: exceptionCaught