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?
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.
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.
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.
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".
Try C#7's Pattern Matching.
Using your example:
if (new StringBuilder("test") is var sb && sb != null) { Console.WriteLine(sb); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With