Use the ? operator to prevent a division by zero : tenary operator « Operators statements « C++ Tutorial






#include <iostream>
using namespace std;

int div_zero();

int main()
{
  int i = 1, j = 0, result;


  // This statement prevents a divide by zero error.
  result = j  ?  i : j;

  cout << "Result: " << result;

  return 0;
}
Result: 0








3.7.tenary operator
3.7.1.Use the ? operator to prevent a division by zero
3.7.2.Using the conditional operator to select output
3.7.3.A Demonstration of the Conditional Operator
3.7.4.Need parentheses around the conditional expression.