Home > Software engineering >  Why it is necessary to initialize a varriable before performing any assignment to it in C?
Why it is necessary to initialize a varriable before performing any assignment to it in C?

Time:05-23

#include <stdio.h>
int main(){
    int sale;
    float comm = 0;
    
    printf("enter the sale amount: ");
    scanf("%d",&sale);
    
    if (sale < 10000) { 
    comm = 0; 
    }
    else if (sale >= 10000 && sale < 15000){
        comm = sale * 0.05;
    } else if (sale >= 15000 && sale < 25000) {
        comm = 0.1 * sale;
    } else if(sale > 25000) {
        comm = 0.15 * sale;
    }
    
    printf("commission is %f",comm);
    
    return 0;
}

in above code comm varriable cant be assigned without intializing to 0 at top. It doesnot throw error but its value is always 0 whenever i print it. what can be the reason behind it ? Please if anybody could explain in detail.

CodePudding user response:

It is onlye "necessary" to initialize comm here for it to have a value if the user enters 25000 -- that's the only value that won't match any of the if statements, so won't assign a value to comm.

There'a also a potential issue if the user enters X or anything else that is not a number. In that case sale will not be set, and will continue to be uninitialized, so any of the cases might trigger.

CodePudding user response:

In this case you don't really have to initialize the comm. And the code is fine, it should be working, maybe you have try a number too small (less than 10000) and that's why it's giving you 0. Try to double check that trying a bigger number :)

  • Related