question about default initialization in c

118 views Asked by At

I am studying for an interview and found this question a bit bewildering. Would appreciate your advice.

What is not initialized by default?

  1. The last variable of a static array in which the first variables are explicitly initialized in a statement.
  2. Dynamic array members assigned using a calloc function.
  3. Global variable.
  4. All data provided here is initialized by default.
  5. The current cursor location when a file is open.
  6. A static variable.
  7. The last character in a static character set.

I think the answer is #1 but not sure about the explanation.

1

There are 1 answers

4
Roy Avidan On
  1. In a static array (or in any array) when it is explicitly initialized all the non-initialized variables values will be 0.
  2. calloc zero the memory it points to.
  3. Global variables values are 0 by default.
  4. Placeholder (this simply means all other options are initialised).
  5. If not opened in append mode (a in fopen) the cursor location will be 0. In append mode it will be the length of the file.
  6. Static variables values are 0 by default.
  7. Static character set (if I understood it correctly) is a char array, and like any other array, when initialized the last char, if uninitialized, will be 0. In the case of a char array, the last char will be the NULL byte and its intention is to be 0 to mark the end of the string.

As you can see, all the options are initialized by default so the answer is 4.

If you are not sure, always check your questions with a simple code:

#include <stdio.h>
#include <stdlib.h>

void test1()
{
    static int arr[5] = { 1,2,3,4 };
    printf("Last variable is %d\n", arr[4]);
}

void test2()
{
    int* arr = (int*)calloc(5, sizeof(int));
    int b = 1;
    for (int i = 0; b && i < 5; i++)
        if (arr[i])
            b = 0;
    if (b) puts("Calloc zero all elements");
    else puts("Calloc doesn't zero all elements");
}

int test3_arg;

void test3()
{
    printf("Global variable default value is %d\n", test3_arg);
}

void test5()
{
    FILE* file = fopen(__FILE__, "r");
    printf("The current cursor location is %ld\n", ftell(file));
    fclose(file);
}

void test6()
{
    static int arg;
    printf("Static variable default value is %d\n", arg);
}

void test7()
{
    static char arg[] = "hello";
    printf("The last character is %d\n", arg[5]); //last one will be the NULL byte (0)
}

int main()
{
    test1();
    test2();
    test3();
    test5();
    test6();
    test7();

    return 0;

    /*
     * Output:
    Last variable is 0
    Calloc zero all elements
    Global variable default value is 0
    The current cursor location is 0
    Static variable default value is 0
    The last character is 0
     */
}