Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing "No/Null/0" as a reference?

Hey I have a little problem, I have this function

EDIT: This is not my function, it's part of a library.

void Input_GetMousePos(
  float *x,
  float *y
);

And I only want to store the Y value, so how would I say "NULL" or "I don't want to write anything" where X is?

The workaround I found is to declare a variable but never use it again, like this

float vx, vy;
_hge->Input_GetMousePos(&vx, &vy);

And then I'm never using "vx" again.

So my question is, is there a way to pass "NULL" or something similar?

Suggestions for title changes are also welcome.

like image 439
PeppeJ Avatar asked Aug 21 '26 22:08

PeppeJ


2 Answers

The point of NULL (and nullptr) is that you can pass them in place of pointers, so to answer your question ("How would I say 'NULL'"), you just say NULL.

_hge->Input_GetMousePos(NULL, &vy);

With C++11, you're encouraged to use nullptr instead of NULL, because it behaves better in some edge cases with templates. Otherwise, both are the same, so if you're more comfortable with NULL, you can very much use it too.

_hge->Input_GetMousePos(nullptr, &vy);

If you've tried that and it crashed or misbehaved, then you're out of luck and a dummy variable to receive the X component is as good as you'll get. Passing nullptr is the convention for this case, so so if it isn't respected, there's nothing you can do with this specific function. There could be other functions that would let you access individual components, though, but we don't have enough information to help with that.

like image 79
zneak Avatar answered Aug 24 '26 13:08

zneak


Well, first of all you don't pass arguments as reference, but as pointers. Using pointers like you do, you can just pass NULL:

void Input_GetMousePos(float *x, float *y) {
  if (x != NULL){
     //you can safely dereference x
  }
  if (y != NULL){
     //you can safely dereference x
  }
}
float vy;
_hge->Input_GetMousePos(NULL, &vy);

You mentioned reference in your question. So lets clear that up too.

Passing by reference would be like:

void Input_GetMousePos(float &x, float &y) {
}
float vx, vy;
_hge->Input_GetMousePos(vx, vy);

Here, the parameters x and y are references. You can't use NULL or anything like for references. You could however use an optional wrapper like boost::optional

Edit

I edited my question, I forgot to include that the function in question is part of a library, and not written by myself

In this case, check the documentation for the function. If it says that arguments are optional, then you can pass NULL, otherwise the function writes at those addresses and you can't pass NULL. You need to provide valid addresses, so you do have to use a variable.

like image 35
bolov Avatar answered Aug 24 '26 14:08

bolov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!