Alex
Alex

Reputation: 91

C - Variable Declaration in If Condition Available in Else?

If I declare a variable in an if condition in C, is that variable also available to the else branch? For example:

if((int x = 0)){
  foo();
} else{
  x++;
  bar(x);
}

Couldn't find the answer, at least not the way that I worded it. Please help.

Upvotes: 2

Views: 2574

Answers (3)

hdeez
hdeez

Reputation: 26

You can't declare a variable like this

 if((int a = 0))

The compiler does not allow the code to run and you get an error

and if you try this

if(something_that_is_false){
        int a = 12;
    }
    else{
        do_something;
    }

again error because they are on the same level and they do not have access to their local variables.

Warning: you can use this code and runs without error

int a;
    if(a=0){
         printf("True");
    }
    else{
        printf("False");
    }

and you will see 'False' in screen because It's like writing

if(0) // and its false!

and for the last

int a;
    if(a=0){
         printf("True");
    }
    else{
        printf("False");
    }

you will see 'True' in screen because It's like writing

if(5) // any number other than zero is true!

Upvotes: 1

shu
shu

Reputation: 139

You can't declare a variable in an if condition in C...

Declare variable in if statement (ANSI C)

If you declare inside the if scope, for example:

if(something){
  int x = 0;
} else{
  x++; // will cause a compilation error
  bar(x);
}

x in 'else' is undeclared because in C a local variable can only be used by statements contained within the code block where they are declared.

Upvotes: 4

user12986714
user12986714

Reputation: 741

Experiment result: one can't declare variables in if conditions. Won't compile.

Upvotes: 0

Related Questions