0

I got 0 as output and I check the value of total inside if there it give 0 everytime

#include <iostream>
using namespace std;
int main()
{

    int n, total, a ;
    cout << "enter number for factorial :";
    cin >> n;
    a = n;
top:
    if (a != 0)
    {
        total *= a;
        a -= 1;
        
        goto top;
    }

    cout << "factorial of " << n << " is " <<total;
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

1 Answers1

-2

In you declaration of total its is initiated with value 0 So when it comes to the statement total *= a which means total = 0 * a

FIX: initialize total with value 1

int total{1};

or

int total = 1;
  • 3
    This is wrong, the value of uninitialized local variables aren't zero. It's *indeterminate*. – Some programmer dude Apr 17 '23 at 14:24
  • 2
    Ehh, uninitialised variables are, generally, *not* automatically initialized to `0` - rather, they have "indeterminate" values. – Jesper Juhl Apr 17 '23 at 14:24
  • 2
    Which does include the _possibility_ of them being `0`. – Chris Apr 17 '23 at 14:25
  • Now i am confused with this intermediate thing – Astronomical_Kabutar Apr 17 '23 at 14:26
  • Local variables that are not explicitly initialized are not required by the standard to hold any particular value. – Chris Apr 17 '23 at 14:28
  • 1
    In your observation the vaues were probably 0 because of your OS and not `c++` . Your OS may initialize memory pages given to your process to 0 when new memory is requested from your application to avoid leaking information from a different program that was running. This initialization only happens when the virtual memory is given the first time to your process. If the memory is reused by your process it will be whatever was in that position. Also as far as c++ is concerned it's undefined behavior to read this memory. The compiler is allowed to assume you can't look at it and optimize it away. – drescherjm Apr 17 '23 at 19:08