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

Jun 3, 2012 at 2:26pm
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");
}
Jun 3, 2012 at 3:18pm
factorial *= --n;

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

while(n>1)
{
   factorial *=n;
   --n;
}
Jun 3, 2012 at 3:19pm
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 Jun 3, 2012 at 3:20pm
Topic archived. No new replies allowed.