0

I created the following function named prime() that checks whether or not a number is prime and returns a boolean value accordingly.

I declared a variable count (but did not initialise it) within the function prime() to keep track of the no. of divisors of the no. being checked.

How's it that instead of a garbage value, does it store value 0 by default?

I have even added a line that prints the value of count after its declaration to confirm my observations.

Please help.

Here's the code snippet:

bool prime(int n)
{
    int count;   //non-static variable count declared, but not initialsed to 0
    printf(" value of count is %i \n", count);  //this printed 0
    bool a;
    for(int x=2; x<=n; x++)
    {
        if (n%x==0)
        count ++;
    }
    if (count == 1)
        a= true;
    else
        a= false; 
    return a;
}
NoDataFound
  • 11,381
  • 33
  • 59
Rimmy
  • 1
  • 7
    `0` *is* a garbage value. – user3386109 Aug 16 '23 at 19:26
  • It could have any value, and reading them before writing to them is undefined behaviour. – ikegami Aug 16 '23 at 19:39
  • @Rimmy - Another tip. `count == 1` is a bool value in itself, so you can just do `return count == 1;` and don't *have to* create a special variable to return. – BoP Aug 16 '23 at 19:50
  • @user3386109 how's it then every time i compile and run it prints the same garbage value(0). – Rimmy Aug 17 '23 at 12:34
  • @ikegami how then it's the same value printed after every compilation and run. – Rimmy Aug 17 '23 at 12:35
  • 1
    There's no point trying to explain undefined behaviour cause literally anything could happen. And any small change in the environment, inputs or code could change that behaviour. – ikegami Aug 17 '23 at 13:17
  • Because the code that precedes the call to `prime` happens to set that area of memory to 0. What you'll find is that some minor change to the code outside of `prime` will cause the `prime` function to stop working correctly. On my system, if I put a `printf("%d\n", 1);` on the line before the call to `prime`, then the garbage value in `count` is 1. You may or may not be able to reproduce that behavior on your system. The behavior depends on the compiler, OS, and hardware that you use. – user3386109 Aug 17 '23 at 17:38

0 Answers0