PeppeJ
PeppeJ

Reputation: 643

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.

Upvotes: 3

Views: 150

Answers (2)

zneak
zneak

Reputation: 138031

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.

Upvotes: 6

bolov
bolov

Reputation: 75688

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.

Upvotes: 3

Related Questions