Home > Back-end >  declaring same variable twice in c
declaring same variable twice in c

Time:12-04

I was just playing around with for loop and wrote below code. When I wrote the second printf statement, compiler asked me to declare the c variable again and when i declared it again i run the code and
got the answer of c 4 as 20. The for loop works correctly. Why is the c 4 expression is producing the output 20?

#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 hides the c declared at the scope of the main function, or it would if the latter were declared before the loop.

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 when the variable in question hasn't had its address taken triggers undefined behavior.

As for why you're getting the value 20, that's part of undefined behavior. There's no guarantee that you'll get any particular value, or even that you'll read the same value twice.

CodePudding user response:

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

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

From the C Standard (J.2 Undefined behavior)

1 The behavior is undefined in the following circumstances:

— The value of an object with automatic storage duration is used while it is indeterminate

Pay attention to that variables with automatic storage duration (declared in a block scope) are not initialized implicitly as variables with the static storage duration that zero initialized if they have arithmetic types.

If you would write for example

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

then the output will be 4.

CodePudding user response:

You have two different variables there, despite both of them being named c, they actually are different things.

The first of them is the one you declared in the for loop, which will no longer be accessible once you exit the loop.

When you declare the second variable after the loop, as you are not initializing it, it will have an indeterminate value.

If you want to use the c variable in the loop after exiting it, what you should do is declare it before the loop:

#include<stdio.h>
int main()
{
  int c;
  for(c =1; c <= 10;   c)
  {
    printf("%d\n",c);
  }
  
  printf("%d ",c 4);
    
  return 0;
}
  • Related