Search code examples
cvariablesdata-structuresinitializationcs50

how to test if a variable is valid or whether it is initialized or not in C?


I am learning C from scratch with Harvard's cs50 course. I've been given an array that's been initialized this way:

int stuff[9][9];

now I have to handle it.
I want to check if each item of the array exists: if not, make stuff[i][j] = 0, otherwise, stuff[i][j]++
But I am searching without resulting on how to check if the variable I am manipulating exists or is valid or whatever: there is no !!stuff[i][j], nor some typeof stuff[i][j] or comparing if (stuff[i][j] == 'undefined') or NULL or any variations of that which I can use...
So, how can I check if a declared variable has not yet been initialized?


update
I've made a test with this:

int a[3];
for(int i = 0; i < 3; i++)
{
    a[i] = a[i] || 0;
}

for(int i = 0; i < 3; i++)
{
    printf("a[%i] -> %i\n", i, a[i]);
}

so, if a[i] didn't exist (i.e. had no value assigned to it), it would receive value 0. this was the output of the printf:

a[0] -> 1
a[1] -> 1
a[2] -> 0

That's good because this approach didn't throw an error, but... what are those numbers??


Solution

  • Assuming the above array is a local variable and not a global, the values of the array are uninitialized and in fact you can't check whether a variable is uninitialized or not, as simply attempting to read such a variable can trigger undefined behavior.

    It sounds like you want all array elements to start with the value 0. The simplest way to do this is to initialize the array as such:

    int stuff[9][9] = {{ 0 }};
    

    Which explicitly sets element [0][0] to 0 and implicitly sets all other elements to 0.

    Alternately, you can create a loop to set all values to 0 to start before doing your "regular" processing.