1
int g_myInt = 0;
int& getIntReference() { return g_myInt; }

void myVarArgFunction( int a, ... ) {
  // .........
}

int main() {
  myVarArgFunction( 0, getIntReference() );
  return 0;
}

In the (uncompiled and untested) C++ code above, is it valid to pass in an int& into a variable argument list? Or is it only safe to pass-by-value?

6
  • You can try it out on something like codepad...paste link: codepad.org/wFaWQrSE Commented Sep 27, 2012 at 3:59
  • why haven't you compiled and tested it? Commented Sep 27, 2012 at 4:04
  • @VaughnCato That's not a reliable way to learn standard behavior. It may work on MSVC and not on other platforms. Commented Sep 27, 2012 at 4:08
  • Agreed, but I think it would be a good first step. Commented Sep 27, 2012 at 4:10
  • FYI: g++ 4.6.3 doesn't complain. Commented Sep 27, 2012 at 4:13

3 Answers 3

2

Section 5.2.2.7 of the C++03 standard says that lvalue-to-rvalue conversion is first performed, so your function should receive a copy of the int instead of a reference.

I tried it with this program using g++ 4.6.3:

#include <iostream>
#include <stdarg.h>

int g_myInt = 7;
int& getIntReference() { return g_myInt; }

void myVarArgFunction( int a, ... )
{
  va_list ap;
  va_start(ap,a);
  int value = va_arg(ap,int);
  va_end(ap);
  std::cerr << value << "\n";
}

int main(int,char **)
{
  myVarArgFunction( 0, getIntReference() );
  return 0;
}

And got an output of 7.

Sign up to request clarification or add additional context in comments.

Comments

0

No, it is not valid to pass in a reference because it is a non-POD type.

From the spec:

If the argument has a non-POD class type, the behavior is undefined.

See this related question on passing std::string, which is non-POD.
Code for reference: http://codepad.org/v7cVm4ZW

1 Comment

The expression getIntReference() has type int which is a POD type.
-1

Yes, you can pass a reference to an int as here. You will be changing the global variable g_myInt if you changed that parameter in the function myVarArffunction...

1 Comment

l think you've got a different language in mind. (Or you're confusing references with pointers.) The va_ stuff doesn't do references, so they're converted to rvalues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.