Search code examples
cinitialization

A function returns different values in every execution


I am somewhat new in coding and I encountered a logical error. The goal is to create a function that tests if the number is divisible from 2 to 10. However, as I have tested, the userInput variable returns the right value, but the value of the function does change every execution. Here is the code:

#include <stdio.h>

int testDivisible(int a) {
    int checker; // checker is intended for counting divisible numbers between 2-10; if returned > 0, then not divisible

    for (int i=2; i<=10; i++) {
        if (a % i == 0) {
            checker = checker + 1;
        }
    }

    return checker;
}

int main() {
    int userInput;

    printf("Enter number: ");
    scanf("%d", &userInput);
    int x = testDivisible(userInput);

    if (x > 0) {
        printf("Is divisible by 1 to 10\n");
    }
    else {
        printf("Is not divisible by 1 to 10\n");
    }

    printf("%d\n", userInput); // intended for testing
    printf("%d", x); // intended for testing
}

However, when I compile and run the code, the results are:

Execution 1:

Enter number: 17
Is divisible by 1 to 10
17
847434400

Execution 2:

Enter number: 17
Is not divisible by 1 to 10
17
-1002102112

Solution

  • In your code,

     int checker; 
    

    is an automatic local variable, which is not initialized explicitly. So, the initial value it contains in indeterminate.

    You must initialize the value to 0.