What will be the output of the following C++ code?

Asked In: BPSC TRE 1.0
#include <iostream>
using namespace std;
long factorial(long a)
{
    if (a > 1)
        return a * factorial(a + 1);
    else
        return 1;
}
int main()
{
    long num = 3;
    cout << num << "!=" << factorial(num);
    return 0;
}
                        

Options

  • A. 6
  • B. 24
  • C. Segmentation fault
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

C. Segmentation fault

Detailed Explanation

Correct Answer: Option C (intended answer)

Explanation:
The recursive call uses factorial(a + 1). Starting with 3, the values keep increasing: 3, 4, 5, 6, and so on. The condition a > 1 remains true, so the base case is never reached. This causes unbounded recursion and may result in a stack overflow or segmentation fault. Strictly speaking, a segmentation fault is not guaranteed by the C++ standard, so Option C is the likely intended exam answer.