0
Union function
Why dose he create the function before main then define it after main ? Why not just once ? And why in main he puts set_id(&item) not (*item) ? https://code.sololearn.com/crEnRhZjVnFH/?ref=app
3 Réponses
+ 3
"Why does he create the function before main then define it after main?
Why not just once?"
https://en.m.wikipedia.org/wiki/Forward_declaration
https://norasandler.com/2018/06/27/Write-a-Compiler-9.html
"And why in main he puts set_id(&item) not (*item)?"
The function accepts pointer to union instance ...
void set_id (union id *item);
Hence an address to union instance <item> is required, as argument, during function call ...
void set_id(union id *item)
{
item->id_num = 42;
}
+ 2
Dark
Yes, the indirection operator (with `*` symbol) is used to dereference the data whose address is carried by a pointer.
The address-of operator (with `&` symbol) is used to get the address of some data in memory. The address-of operator is used here (&item) to get address of <item> in memory.
If <item> itself was a pointer, then we can directly use it like so (item) because a pointer carries memory address. In such case, there will be no need to use address-of operator `&`.
"If I defined a function with a pointer as a parameter, when I call it I have to use the adress not the pointer itself as an argument?"
It depends, if the argument you want to pass WAS a pointer, then just go ahead pass it on. But if the argument WAS NOT a pointer, like what we have here - remember <item> is a `union` instance, then we need to pass address of <item>, and that's where and why we use the address-of operator `&`
* About operators:
https://en.cppreference.com/w/c/language/operator_precedence
+ 1
Ipang u mean *item not same as &item ?
and if i defined a function with a pointer as a parameter, when i call it i have to use the adress not the pointer itself as an argument ?