cfor-loopvariable-initialization

Why does this C code take so long to compile and execute if the variable is not initialized?


The following C code takes so long to compile and execute.

#include <stdio.h>

int main()
{
    int max;
    printf("Enter a value for max: ");
    scanf("%d", &max);

    for (int i=0; i<max; i++)
    {
        printf("%d\t", i);
    }

    return 0;
}

But, If I initialize the max variable with some number like

int max = 0;

The Compilation and execution is almost instantaneous. Can someone explain why?

Edit:

When I printed the value of the variable max before my input, it showed 2203648 (some garbage value). Instead of "int max = 0", if i assign

int max = 2203648;

the compilation and execution takes the same long time. But, as mentioned earlier, if i assign max say

int max = 200;

the compilation and execution is instantaneous. Does it have to do anything with the pre-assigned garbage value?

Also, this problem occurs only in windows computers, I tested with ubuntu, and the compilation and execution is instantaneous in both version of the code.

In Windows 10:

compilation and execution, as of "Enter a value for max: " appears on screen:

without variable initialization = around 8 seconds

with variable initialization = instantaneous

compiler - gcc


Solution

  • The scanf is failing. Check the return value.

    i.e.

       if (scanf("%d", &max) != 1) {
          fprintf(stderr, "Unable to read max");
          exit(1);
       }
    

    max is probably some large value hence the large amount of time

    EDIT

    The delay to see the prompt is that the printf is in a buffer and will not be displayed until the loop completes