Home > Mobile >  `bool n;` `n ;` is invalid but `n=n 1;` or `n=n 3` such things works what's the significance o
`bool n;` `n ;` is invalid but `n=n 1;` or `n=n 3` such things works what's the significance o

Time:11-07

Code C 17

#include <iostream>

int main()
{
    bool n=-1;
    n  ;    // Not compiles
    n=n 3;  // This compiles
    return 0;
}

Output

ISO C  17 does not allow incrementing expression of type bool

So I am not understanding the significance of allowing addition but not increment.

CodePudding user response:

As you can see in section 5.3.2 of standard draft N4296, this capability has been deprecated

The operand of prefix is modified by adding 1, or set to true if it is bool (this use is deprecated)

Please note that the expression n=n 3; is not a unary statement, and it's not something that we could call deprecated. If we call it deprecated, the first problem is that there will be no implicit conversion from bool to int, for example. Since they don't know what you want to do with a not unary statement, it is reasonable that the below code gives you the output 2 for i(Deprecating this is not acceptable)

bool b = true;
int i = 1;
i = i   b;

In your example, what happens is implicit conversion from bool->int->bool

bool n=-1;
n  ;    // It's a unary statement(so based on the draft, it would not compile)
n=n 3;  // This compiles (type(n 3) is now int, and then int is converted to bool)

Why unary increment is deprecated?

I use Galik's comment for completing this answer:

With b if you promote the bool b to int you end up with an r-value temporary. You can't increment r-values. So in order for b to have ever worked it must have been a bool operation, not a promotion to an arithmetic value. Now, that bool operation has been banned. But promotions remain legal so arithmetic that uses promoted values is fine.

  • Related