-2

If post fix decrement(--x) is equal to (x-1) so why when I change factorial(n-1) to factorial(--n)it gives me a logical error of output = 0

#include<stdio.h>

int factorial (int n) {
    int fact=1;
    if (n>=1) {
        fact=n*factorial(n-1);
    }
    return fact;
}

void main (void) {
    int x , y ;
    printf("Please Enter a Number : ");
    scanf("%d",&x);
    y=factorial(x);
    printf("Factorial = %d ",y);
}
Gerhardh
  • 11,688
  • 4
  • 17
  • 39
  • 1
    "If post fix decrement(--x) is equal to (x-1)" It is not. `x-1` does not change `x`, while `--x` does. The value these expressions evaluate to, are equal but not the whole behaviour – Gerhardh Aug 14 '23 at 15:03
  • `--x` is a ***pre***-fix decrement, not a post fix. And, `--x` is equal to the entire statement `x = x-1;` – abelenky Aug 14 '23 at 15:04
  • 1
    Related: https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior . If you use `--n` you cannot rely on any evaluation order in `n * factorial (--n)`. You can only be sure that `--n` is evaluated before calling the function but you cannot be sure if `n` or `--n` is evaluated first. – Gerhardh Aug 14 '23 at 15:08
  • Suppose you had the code `n*factorial(--n)`, and before this line, `n` was equal to `1`. Step by step, what do you think should happen at this point? Why? – Karl Knechtel Aug 14 '23 at 15:09

3 Answers3

3

Making that change:

fact=n*factorial(--n);

Results in an expression which both reads and writes n without an intervening sequence point, which triggers undefined behavior in your code.

dbush
  • 205,898
  • 23
  • 218
  • 273
2

The difference is that

factorial(--n)

changes the value of n while

factorial(n-1)

doesn't change the value of n

Further, code like

fact=n*factorial(--n);

has undefined bahavior as it both uses and changes n in the same statement (i.e. without a sequence point in between).

For this part:

If post fix decrement(--x) is equal to (x-1)

  1. --x isn't post-fix. It's pre-fix

  2. They are not equal! --x changes the value of x while x-1 doesn't

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
0

factorial(n-1) to factorial(--n)it gives me a logical error of output = 0

It is undefined by C language standard.

But probable explanation of the observable behaviour is: if n == 1 then

fact=n*factorial(--n);

n will become zero before calling factorial. So if n == 1 then it will become

fact=0*factorial(0);

Which is always 0.

0___________
  • 60,014
  • 4
  • 34
  • 74
  • 1
    The behavior of `n*factorial(--n)` is not defined by the C standard. `n` **may** become zero before it is used for the left operand of `*`, and that is likely what OP is experiencing, but it should be stated that the behavior is not defined, not that “`n` **will** become” anything. – Eric Postpischil Aug 14 '23 at 15:14