Ralph Lee Stone
Ralph Lee Stone

Reputation: 43

Uninitialized Error

What do I need to do to fix the uninitialized error on my program? The program is suppose to print the number of divisors a number has but keeps displaying an error saying the variable c is uninitialized.

/*
/ Name: Ralph Lee Stone
/ Date: 10/10/2013
/ Project: RLStone3_HW_08
/ Description: This program gets a positive value and determines the number of divisors    it has.
*/
#include <iostream>
using namespace std;

int DivisorCount(int x)
{
  int counter = 0;
  for(int c; x < c; c++)
  {
    if (x%c==0)
     counter++;
  }
  return counter;
}
int main()
{
  int x;
  cout << "Please a positive value: ";
  cin >> x;
  cout << x << "has this many divsors: " << DivisorCount(x);
}

Upvotes: 0

Views: 1358

Answers (5)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158629

c has an indeterminate value in your for loop here:

for(int c; x < c; c++)
        ^

you need to initialize it to a value for example:

for(int c=2; x < c; c++)

it will need to be greater than 0(perhaps 2 since you probably don't want 1 as a divisor) since you are using it in the modulus operation here:

if (x%c==0)

and modulus by 0 is undefined behavior as per the draft C++ standard section 5.6 Multiplicative operators paragraph 4 says:

[...]If the second operand of / or % is zero the behavior is undefined.[...]

It looks like you may have flipped your ending condition and it should go from c < x instead of x < c.

Upvotes: 2

Walter
Walter

Reputation: 45484

for(int c; x < c; c++) // what do you think is the value of c initially?
                       // and when do you think the loop will stop?

edit I don't know what you meant with unresolved external errors. If I correct your bugs

for(int c=1; c<x; c++) 

it compiled and gave reasonable results: 5 has 1 divisor, 9 has 2, 8 has 3, and 12 has 5.

Upvotes: 1

Daniel Frey
Daniel Frey

Reputation: 56921

You need to initialize it with some value:

for(int c = 1; x < c; c++)
//        ^^^ here

also, did you mean to write c < x instead of x < c?

Upvotes: 5

user229044
user229044

Reputation: 239571

c isn't initialized:

for(int c; x < c; c++)

This declares (but does not initialize) c, and then immediately accesses it to test whether x < c.

Upvotes: 1

digital_revenant
digital_revenant

Reputation: 3334

You are not giving any initial value to c

for(int c; x < c; c++)

change to

for(int c=0; x < c; c++) //assign a value

Upvotes: 1

Related Questions