Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default value of a char in an uninitialized array, in C?

Given the following declaration:

char inputBuffer[12];

What is the default value of either char within the array? I'm interested in knowing this because if at any time I want to clear a position in the array, I need to know what value to give it.

like image 670
Andrei Oniga Avatar asked Jul 17 '14 07:07

Andrei Oniga


2 Answers

The array elements have indeterminate value except if the array it is defined at file-scope or have static storage-class specifier then the array elements are initialized to 0.

 #include <stdio.h>

 char inputBuffer1[12];          // elements initialized to 0
 static char inputBuffer2[12];   // elements initialized to 0

 void foo(void)
 {
     char inputBuffer3[12];         // elements have indeterminate value!
     static char inputBuffer4[12];  // elements initialized to 0
 }
like image 81
ouah Avatar answered Sep 24 '22 18:09

ouah


If char inputBuffer[12]; is global or static, it is initialized with \0

char inputBuffer1[12];  /* Zeroed */
static char inputBuffer1[12];  /* Zeroed */

int fn()
{
  static char inputBuffer3[12];  /* Zeroed */
}

If it is local to function, it contains garbage value.

int fn2()
{
  char inputBuffer4[12];  /* inderminate value */
}

Quoting from ISO/IEC 9899:TC2 Committee Draft — May 6, 2005 WG14/N1124

Section 6.7.8 Initialization (emphasis mine)

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these rules.

like image 36
Mohit Jain Avatar answered Sep 23 '22 18:09

Mohit Jain