By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,290 Members | 1,666 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,290 IT Pros & Developers. It's quick & easy.

Passing "++a" to a function taking "int&"

P: n/a
Consider this code:

void foo(int& i)
{
i += 10;
}

int main()
{
int a = 1;
foo(++a);
foo(a++);
}

Using gcc 3.3.5 (with -Wall -W -pedantic -ansi) the first foo() call
is ok, but the second one causes an error.

I assume that this is indeed what the C++ standard says. However,
I would like to make sure that it indeed is so. (I'm more interested
in the "foo(++a)" working than the "foo(a++)").
Jun 7 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Juha Nieminen wrote:
Consider this code:

void foo(int& i)
{
i += 10;
}

int main()
{
int a = 1;
foo(++a);
foo(a++);
}

Using gcc 3.3.5 (with -Wall -W -pedantic -ansi) the first foo() call
is ok, but the second one causes an error.
That's because 'a++' does not yield an l-value, bun an r-value, IIRC,
and a non-const reference cannot be bound to an r-value (a temporary).
'++a' yields an l-value, the object itself, after it's incremented.
I assume that this is indeed what the C++ standard says. However,
I would like to make sure that it indeed is so.
Yes, it is indeed so.
(I'm more interested
in the "foo(++a)" working than the "foo(a++)").


V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jun 7 '06 #2

P: n/a
Juha Nieminen wrote:
Consider this code:

void foo(int& i)
{
i += 10;
}

int main()
{
int a = 1;
foo(++a);
foo(a++);
}

Using gcc 3.3.5 (with -Wall -W -pedantic -ansi) the first foo() call
is ok, but the second one causes an error.

I assume that this is indeed what the C++ standard says. However,
I would like to make sure that it indeed is so. (I'm more interested
in the "foo(++a)" working than the "foo(a++)").


Yes, it is correct, the second passes a temporary (the result of a++) to
a function that takes a non-const reference. The first simply passes a.

--
Ian Collins.
Jun 7 '06 #3

P: n/a
a++: rerun a const object

const Type Type::operator++(int)
{
Type oldvalue = *this;
++(*this);
return oldvalue;
}

++a: return a no-const reference

Type& Type::operator++()
{
*this+=1;
return *this;
}

Jun 8 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.