! and ~ in an enum data type

What is accurate detail difference on operator ! and ~ in an enum data type operation (as read one's code of it)?

isn't just the same negation?
> isn't just the same negation?
Well you could always try it you know.

1
2
3
4
5
6
7
8
9
#include<iostream>      
using namespace std;
enum foo { bar = 42 };
int main ( ) {
  foo x = bar;
  cout << -x << endl;
  cout << ~x << endl;
  cout << !x << endl;
}


No, they're not the same.
there are 2 types, logical and bitwise. Logical is the whole value, bitwise is per bit. 1234 is just true (and collapses to 1 if used thusly), logically, because its not zero. but bitwise not of 1234 is some totally different value.
> operator ! and ~ in an enum data type

These arithmetic operators are applied after integral promotion; so the effect is the same as operator ! and ~ on the promoted integral data type.

Since there is no implicit conversion from a scoped enumeration to an integral type, these operators are not available for scoped enumerations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <concepts>

enum class A { zero = 0, one = 1 };

enum B : short { neg = -10, pos = +10 };

enum C : unsigned long long { ccc = 5 };

int main()
{
    A a = A::zero ; // scoped enumeration

    // !a ; // *** error *** there is no no operator !
    // ~a ; // *** error *** there is no no operator ~

    B b = neg ; // unscoped enumeration
    auto const x = ~b ; // integral promotion B => short => int
    static_assert( std::same_as< decltype(~b), int > ) ; // ~b is an int
    static_assert( std::same_as< decltype(!b), bool > ) ; // !b is a bool (! is applied to the promoted int value)

    C c = ccc ; // unscoped enumeration
    auto const y = ~c ; // integral promotion C => unsigned long long
    static_assert( std::same_as< decltype(~c), unsigned long long > ) ; // ~c is an unsigned long long
    static_assert( std::same_as< decltype(!c), bool > ) ; // !b is a bool (! is applied to the promoted unsigned long long value)
}
Topic archived. No new replies allowed.