×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

What happens if we use an uninitialized array in C language?

Using an uninitialized array in C programming language: Here, we will learn that what happens if we use an uninitiated array in C language?
Submitted by IncludeHelp, on May 28, 2018

What happens if we use an uninitialized array in C language?

If we use any uninitialized array in C program, compiler will not generate any compilation and execution error i.e. program will compile and execute properly.

If the array is uninitialized while declaring and even after the declaration if you do not initialize then, you may get unpredictable result.

Therefore, it is recommended to write a good and safe program you should always initialize array elements with default values.

Example

Consider the program:

#include <stdio.h>

int main(void) 
{
	int a[5];
	int b[5] = {0};
	int c[5] = {0,0,0,0,0};

	int i; //for loop counter

	//printing all alements of all arrays
	printf("\nArray a:\n");
	for( i=0; i<5; i++ )
		printf("arr[%d]: %d\n",i,a[i]);
	
	printf("\nArray b:\n");
	for( i=0; i<5; i++)
		printf("arr[%d]: %d\n",i,b[i]);
	
	printf("\nArray c:\n");
	for( i=0; i<5; i++ )
		printf("arr[%d]: %d\n",i, c[i]);
	
	return 0;
}

Output

    Array a:
    arr[0]: -1948874610
    arr[1]: 32764
    arr[2]: 1249250789
    arr[3]: 11047
    arr[4]: 1

    Array b:
    arr[0]: 0
    arr[1]: 0
    arr[2]: 0
    arr[3]: 0
    arr[4]: 0

    Array c:
    arr[0]: 0
    arr[1]: 0
    arr[2]: 0
    arr[3]: 0
    arr[4]: 0

See the output, array a was uninitialized so the values are garbage while array b and c are initialized so the all element's values 0.




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.