Home > OS >  Using a same variable twice in c
Using a same variable twice in c

Time:12-04

whenever I run this code I get the answer of c 4 as 20.(the for loop runs perfectly)

#include<stdio.h>

int main()
{
  for(int c =1; c <= 10;   c)
  {
    printf("%d\n",c);
  }
    
  int c;
  printf("%d ",c 4);
    
  return 0;
}

CodePudding user response:

Two have two separate variables named c, each of which resides at a different scope.

The scope of the c declared in the for loop is the for statement itself and its body. This masks the c declared at the scope of the main function.

Also, the c declared in the scope of main is uninitialized, and you attempt to read its value. The value of an uninitialized variable is indeterminate, and reading such a value triggers undefined behavior.

CodePudding user response:

The program has undefined behavior because the variable c in this code snippet was not initialized

int c;
printf("%d ",c 4);

CodePudding user response:

for(int c =1; c <= 10;   c) // scope of 'c' within loop itself
{
  printf("%d\n",c);
}

int c; // scope in main function having garbage value [not initialized]
printf("%d ",c 4);
  •  Tags:  
  • c
  • Related