Home > database >  Initialization of variables in c language
Initialization of variables in c language

Time:12-05

I have bought a C programming course on udemy. The tutor always initializes the variable to 0 before taking the inputs from the user.

int a = 0;


printf("Enter the number: \n");


scanf("%d",&a);


printf("The number you have entered is %d",a);


return 0;

Is it necessary to do so?

CodePudding user response:

In order to make the behavior of a C program fully defined, it is necessary to give an object (a variable) a value before using the object’s value. It is not necessary to do this by initialization in the definition of the object. It can be done by giving it a value via scanf or assignment.

Initializing an object in its definition can ensure it has a value in case later programming errors mistakenly fail to give it a value. It can also ensure it has a value in case the scanf does not give it a value because the input does not match the scanf format. While this initialization ensures the object has a value, it can mask programming errors.

CodePudding user response:

It's a common practice to set a value to the variables when you define them. Sometimes, you get bad errors when try to operate with variables that weren't initializated with a value and most compilers would issue a warning about using an uninitialized variable.

  • Related