Why does intpromote spew warnings for ~ operator?
Stefan Koch
uplink.coder at googlemail.com
Tue Sep 14 12:04:12 UTC 2021
On Tuesday, 14 September 2021 at 09:07:24 UTC, Alexey wrote:
>```c
> #include <stdio.h>
>
> int main(int argc, char* argv[])
> {
> unsigned char a = 0b100;
> unsigned char b = ~a;
> return 0;
> }
> ```
> will C also silently promote a to int and silently truncate it
> to uchar? - should those under-carpet things also happen in D
> just to save C's behavior?
Yes it will.
you can convince yourself if you run this.
```c
#include <stdio.h>
#include <stdbool.h>
char* binPrint(int v, char* buffer);
#define bits(v) (sizeof(v) * 8)
int main(int argc, char* argv[])
{
char buffer[bits(int) + 1];
unsigned char a = 0b100;
printf("a: %d -- %s\n", a, binPrint(a, &buffer[0]));
unsigned char b = ~a;
unsigned int c = ~a;
printf("uchar b: %u -- %s\n", b, binPrint(b, &buffer[0]));
printf("uint c: %u -- %s\n", c, binPrint(c, &buffer[0]));
}
char* binPrint(int v, char* buffer)
{
int last_set_bit;
for(int bit_idx = 0; bit_idx < bits(v); bit_idx++)
{
bool bit_set = (v & (1 << bit_idx));
buffer[bits(v) - bit_idx] = bit_set ? '1' : '0';
if (bit_set) last_set_bit = bit_idx;
}
buffer[bits(v) + 1] = '\0';
return &buffer[bits(v) - last_set_bit];
}
#undef bits
```
More information about the Digitalmars-d
mailing list