Home > database >  Warning about uninitialized local variable
Warning about uninitialized local variable

Time:09-26

int student = 1;
float mark, avg, total = 0;

while (mark != -1.00)
{
    printf("Enter marks for Student %d (or -1 to stop): ", student);
    scanf("%lf", &mark);
    total  = mark;
    student  ;
}

CodePudding user response:

At the beginning variable mark has no initialized value, so its value is unknown.

In next line you are comparing it in while loop. But you haven't read the value of mark from user yet, so the value being compared is something unknown.

I suspect you wanted to use a do { ... } while loop:

do {
    printf("Enter marks for Student %d (or -1 to stop): ", student);
    scanf("%lf", &mark);
    total  = mark;
    student  ;
} while (mark != -1.00);

Also few notes:

  • %lf is for double, use %f for float
  • Due to limited precision of floating numbers (see this), the comparison mark != -1.00 isn't the best practice. Usually in such situation you would do mark - (-1.00) < epsilon, where epsilon is acceptable error. But it doesn't apply in this case, as you only use it as flag.
  • You should also check if mark isn't -1.00 before adding to total, thus your loop should be:
while (1) {
    printf("Enter marks for Student %d (or -1 to stop): ", student);
    scanf("%f", &mark);
    if (mark != -1.00) {
        total  = mark;
          student;
    } else {
        break;
    }
}

CodePudding user response:

while (mark != -1.00)

mark is used not initialized here thus the warning. It is undefined behaviour.

  •  Tags:  
  • c
  • Related