Sujet : Re: how cast works?
De : thiago.adams (at) *nospam* gmail.com (Thiago Adams)
Groupes : comp.lang.cDate : 08. Aug 2024, 12:35:06
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v92aha$3u7l7$2@dont-email.me>
References : 1 2
User-Agent : Mozilla Thunderbird
On 07/08/2024 17:08, Keith Thompson wrote:
Thiago Adams <thiago.adams@gmail.com> writes:
How cast works?
Does it changes the memory?
For instance, from "unsigned int" to "signed char".
Is it just like discarding bytes or something else?
I also curious about how bool works.
Values converted to bool became 0 or 1.
When this conversion happens, at read or write? Both?
How much does it cost?
I also learned we cannot cast a pointer to nullptr_t.
But we can read a union with nullptr. In this case the value is 0
similar of what happens with bool.
Sample
----------------
#include <stdio.h>
struct value {
int type;
union{
unsigned int ui;
_Bool b;
typeof(nullptr) p;
} ;
};
int main(){
struct value v;
v.ui = 123;
printf("%d / ", v.ui); //123
printf("%d / ", v.b); //1
printf("%p", v.p); //(nil)
}
--------
Using compiler explorer to understand bool.
void f(int i)
{
bool b = i;
printf("%d / ", b);
}
cmp dword ptr [rbp - 4], 0 //i think it checks 0 here
setne al
and al, 1
mov byte ptr [rbp - 5], al
I think it convert at write in this case..but for union it converts
when we read. This is why
printf("%d / ", v.b); //1
prints 1
void f()
{
union {
unsigned int ui;
_Bool b;
} v;
v.ui = 123;
printf("%d / ", v.b);
}
Where b.b is converted to 1?
f:
push rbp
mov rbp, rsp
sub rsp, 16
mov dword ptr [rbp - 4], 123
mov al, byte ptr [rbp - 4]
and al, 1
movzx esi, al
lea rdi, [rip + .L.str]
mov al, 0
call
printf@PLT add rsp, 16
pop rbp
ret
I think is at
al, 1
so the compiler uses 123 & 1 to cast number to bool.