Hassan Hassan - 9 months ago 31
C++ Question

Modulo behaviour with if statement in C++

Why this code returning 5. First if is returning 5%2 = 1 and if false on if(1). why is so.

#include <iostream>

using namespace std;

int fn_test(int i=5)
if(i%2) return i++;
return fn_test(i-1);
int main()
{ int test=fn_test(5);
cout<< " this is out put " << test;
return 0;


The result of 5%2 is 1 as you notice, which is non-zero and therefore "true". Only zero is "false", everything else is "true".

That means you do return i++, which returns the old value of i (i.e. 5) before incrementing i.