Я бы спросил, из-за чего она НЕ появляется. && — вроде ленивый, соответственно если y == false, то присваивания не будет -> x — не инициализирован. всегда должна быть ошибка.
Здравствуйте, Jack128, Вы писали:
_FR>>А из-за чего ошибка появляется?
J>Я бы спросил, из-за чего она НЕ появляется. && — вроде ленивый, соответственно если y == false, то присваивания не будет -> x — не инициализирован. всегда должна быть ошибка.
Здравствуйте, _FRED_, Вы писали:
_FR>А из-за чего ошибка появляется?
Потому что так устроена спецификация. Нам нужно, чтобы x была definitely assigned в then-ветке.
5.3.3.5 If statements
For an if statement stmt of the form:
if ( expr ) then-stmt else else-stmt
...
• If v is definitely assigned at the end of expr, then it is definitely assigned on the control flow transfer to then-stmt and to either else-stmt or to the end-point of stmt if there is no else clause.
• If v has the state “definitely assigned after true expression” at the end of expr, then it is definitely assigned on the control flow transfer to then-stmt, and not definitely assigned on the control flow transfer to either else-stmt or to the end-point of stmt if there is no else clause.
...
• Otherwise, v is considered not definitely assigned on the control flow transfer to either the then-stmt or else-stmt, or to the end-point of stmt if there is no else clause.
(Нерелевантные части убраны.)
Итак, после expr-cond ? true : false нужно, чтобы x было definitely assigned или definitely assigned after true expression.
Смотрим дальше:
5.3.3.28 ?: expressions
For an expression expr of the form expr-cond ? expr-true : expr-false:
...
• The definite assignment state of v after expr is determined by:
o If expr-cond is a constant expression (§7.19) with value true then the state of v after expr is the same as the state of v after expr-true.
o Otherwise, if expr-cond is a constant expression (§7.19) with value false then the state of v after expr is the same as the state of v after expr-false.
o Otherwise, if the state of v after expr-true is definitely assigned and the state of v after expr-false is definitely assigned, then the state of v after expr is definitely assigned.
o Otherwise, the state of v after expr is not definitely assigned.
У нас expr-cond не константа и x не является definitely assigned после expr-false. Поэтому срабатывает последний пункт.
Неформальное же объяснение такое: вместо expr-cond ? true : false могло бы быть написано expr-cond ? true : true, и тогда переменная могла бы быть не инициализирована в then-ветке. Однако компилятор не отличает эти два случая, так что приходится пессимизировать ситуацию.
А нельзя ли к этюдам етим каких-нибудь картинок с сиськаме добавлять, ато они (этюды) не всем понятны, нов мести с тем хочется быть в общей тусовки. Пасиб