Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we define a variable inside an if statement?

Maybe this question has been answered before, but the word if occurs so often it's hard to find it.

The example doesn't make sense (the expression is always true), but it illustrates my question.

Why is this code valid:

StringBuilder sb; if ((sb = new StringBuilder("test")) != null) {     Console.WriteLine(sb); } 

But this code isn't:

if ((StringBuilder sb = new StringBuilder("test")) != null) {     Console.WriteLine(sb); } 

I found a similar question regarding a while statement. The accepted answer there says that in a while statement, it would mean the variable would be defined in each loop. But for my if statement example, that isn't the case.

So what's the reason we are not allowed to do this?

like image 892
comecme Avatar asked Jul 02 '11 19:07

comecme


People also ask

Can you define a variable in an if statement?

If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement. It allows us to write terser, clearer code, while also avoiding limiting the scope of a variable.

Can you declare a variable in an if statement in C?

No. That is not allowed in C. According to the ANSI C Grammar, the grammar for the if statement is IF '(' expression ')' statement . expression cannot resolve to declaration , so there is no way to put a declaration in an if statement like in your example.

Can you define variable in IF statement Python?

Yes. It is also true for for scope. But not functions of course. In your example: if the condition in the if statement is false, x will not be defined though.

Can we initialize a variable in if condition?

C++17 If statement with initializer Now it is possible to provide initial condition within if statement itself. This new syntax is called "if statement with initializer".


1 Answers

Try C#7's Pattern Matching.

Using your example:

if (new StringBuilder("test") is var sb && sb != null) {     Console.WriteLine(sb); } 
like image 184
Jecoms Avatar answered Oct 07 '22 14:10

Jecoms