Hello everyone, I am new to this forum and programming in general and had a quick question.
In the code below, I was wondering why it was necessary to initialize the variables. I understand the general purpose of initialization(no garbage data) but I don't see what the point is here because we declare the variable and we ask the user to tell us what the variable represents before we ever use the variable.

#include <stdio.h>
int main(void)
{
int base, power, index;
long answer;
base = 0;
power = 0;
answer = 1.00;
printf("Enter a base number: ");
scanf("%d", &base);
printf("Enter a power to raise the base to: ");
scanf("%d", &power);
for(index = 1; index <= power; index++)
answer = answer * base;
printf("%d raised to the power of %d is %ld.", base, power, answer);
getchar();
getchar();
return 0;
}

Its a good idea to initialize local variables but if the variables going to be assigned to right away then you can leave them uninitialized...Myself, I always initialize local variables. I like knowing that my program is in a valid state.

One case that's essential is pointers. A pointer should be defined with a valid memory address or set to NULL.

It is not necessary to initialize variables. The problem you run into with memory that is not initialized is that if you try to read it you could end up with strange behavior. As gerard4143 mentioned, this is doubly important with pointers as anything other than a NULL value could be considered valid by your program although it may point to memory not owned by your program.

Member Avatar for rolf.becker

If you do not enter a number but anything else, the scanf will fail and the variables will remain uninitialized.

rolf.becker is absolutely right.....
if someone enter a character as a base then....base value will be printed as 0 and u can understand that user don't input valid input........This way intialization of variable is important.

Unless, of course, they entered a 0...
The proper way to check if a printf/scanf operation succeeded is to check it's return value and evaluate the state of the stream.
Initializing variables to verify input is problematic at best and should be avoided.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.