Reaching a C # position and a specific task

I am puzzled by the csc reaction to this code:

{ int i; if (false) { i++; // uninitialized, but allowed by compiler } if (false && i < 30) // uninitialized, but allowed by compiler { } if (false && i < 30) // uninitialized, but allowed by compiler { i++; // NOT ALLOWED by compiler?? } } 

In this code, I have three if and one uninitialized local variable i. CSC is smart enough to tolerate my use in the first and second cases, since it can say that the code in which I am used is not available. However, in the third case, he complains about the increase in "use of the unassigned local variable i". Why does he correctly detect that I am in unreachable code in the first two ifs, but not in the third (which is nothing but a combination of the first two cases?

+4
source share
1 answer

This is explained in section 8.7.1 of the C # 5 specification:

The first built-in if is available if the if is available and the logical expression does not have a constant false .

Although we can reason that this condition:

 false && i < 30 

always false , this is not a constant expression in accordance with the rules of the language (7.19), therefore the first built-in statement in the body is available.

This is not that everything related to && is not false. This is normal, for example:

 if (false && true) { i++; } 

... but since the expression i < 30 not constant, your original expression is not constant. This is true, although we know that expression will never be appreciated.

The language can decide that any && expression, where the LHS has a constant false expression, was also a constant expression with the value false , but this is not so. (This will be only a small added difficulty, but the level of benefits is very small.)

+7
source

Source: https://habr.com/ru/post/1480277/


All Articles