Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return an int or pass an int pointer -- whats better?

Tags:

c

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;
}
like image 768
emge Avatar asked Jun 30 '10 14:06

emge


People also ask

Which is better pass by reference or pass by pointer?

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.

Is passing by reference faster than pointer?

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.

When should you pass a pointer?

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 is it sometimes desirable to pass a pointer to a function as an argument?

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.


1 Answers

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);
like image 169
Michael Kristofik Avatar answered Nov 15 '22 09:11

Michael Kristofik