Home > Enterprise >  How to use variable outside of if-statement?
How to use variable outside of if-statement?

Time:01-04

i'm very new to C programming. I wanted to know how do i use a variable declared in an if-statement (or just any function in general) outside of it? Example:

int x = 100;
int y = 0;
 
if (x > 5){
        int y = x / 5;
        printf("%d\n",y);   // outputs 20
    }

    printf("%d",y);    // outputs 0 but I wanted 20

CodePudding user response:

int x = 100;
int y = 0;
 
if (x > 5)
{
  int y = x / 5;   //<< here you declare a new y variable  
  printf("%d\n",y);   // outputs 20
}

printf("%d",y);    // outputs 0 but I wanted 20

You could as well write this, which would be equivalent to your original code:

int x = 100;
int y = 0;
 
if (x > 5)
{
  int foo = x / 5;
  printf("%d\n",foo);   // outputs 20
}

printf("%d",y);    // outputs 0 but I wanted 20

Inside the braces you declare a new y variable that is totally distinct from the y variable you've declared in the second line of your code. The only thing these two variables have in common is their name.

You want this:

int x = 100;
int y = 0;
 
if (x > 5)
{
  y = x / 5;            // drop the int keyword here
  printf("%d\n",y);     // and the other y variable will be used.
}

printf("%d",y);

CodePudding user response:

The command scanf, with syntax: scanf(“string”,var_list); Returns a true value, that is 1, when it reads a value from a user during runtime, else it returns 0. Executes the statement if a value is input during runtime, else it gets skipped.

  • Related