which of these two is better?
void SetBit(int *flag, int bit)
{
*flag |= 1 << bit;
}
Or
int SetBit(int flag, int bit)
{
flag |= 1 << bit;
return flag;
}
The difference between pass-by-reference and pass-by-pointer is that pointers can be NULL or reassigned whereas references cannot. Use pass-by-pointer if NULL is a valid parameter value or if you want to reassign the pointer. Otherwise, use constant or non-constant references to pass arguments.
We take advantage of this small size when storing data and when passing parameters to functions. It's much faster and memory-efficient to copy a pointer than to copy many of the things a pointer is likely to point to. A reference is stored in as many bytes as required to hold an address on the computer.
You pass a pointer to pointer as argument when you want the function to set the value of the pointer. You typically do this when the function wants to allocate memory (via malloc or new) and set that value in the argument--then it will be the responsibility of the caller to free it.
Why it is sometimes desirable to pass a pointer as an argument to a function? Pointers can also be passed as an argument to a function like any other argument. Instead of a variable, when we pass a pointer as an argument then the address of that variable is passed instead of the value.
I like the second one because it doesn't have any side effects. If you want to modify flag
, you can simply assign the result to itself:
flag = SetBit(flag, 4);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With