The variable 'factorial' is being used without being initialized.

This is the message I get and no matter how much I searched, I can't seem to find the solution let alone the perfect explanation to that error.

I want the program to request a number and calculate it's factorial.

I just started learning C++. I'm a newbie.

This is my code:

#include "stdafx.h"
#include <iostream>

using namespace std;

int get_factorial(int n)
{
int factorial;
while(n > 1)
{
factorial *= --n; // the compiler, Microsoft C++ 2008 points the error to this line.
}
return factorial;
}

void main()
{
int n;
int factorial;
cout<<" Insert value :";
cin>>n;

factorial = get_factorial(n);
cout<<" The answer is "<<factorial<<endl;

system("pause");
}
factorial *= --n;

the ide dont know " *=--"
you can try this:

while(n>1)
{
   factorial *=n;
   --n;
}
factorial *= --n;

This means:

factorial = factorial * (--n);

So tell me, the first time you get to this bit, what value does factorial have? There's no way to tell. It could be any value. Completely random, because you didn't give the variable an initial value.

Here is how to give the variable an initial value of zero:
int factorial = 0;

and here is how to give the variable an initial value of fifty-six:
int factorial = 56;

Now you think about what value it should have to start, and do that.

While I'm here, this:
void main()
is not C++. In C++, main returns an int, like this:
int main()
Last edited on
Topic archived. No new replies allowed.