What does this mean?

P

Protoman

What does this do?

int& fn(int& arg){arg++;return arg;}
//later
int y;
fn(y)=5;

Why can you do it? What do you use it for? Thanks!!!
 
D

Dan Cernat

See below

Protoman said:
What does this do?

int& fn(int& arg){arg++;return arg;}
//later
int y;
fn(y)=5; <-- use of uninitialised variable y
according to the body of fn, you may get an overflow. otherwise the
statement above will initialise y with 5
Why can you do it?
Why not?
What do you use it for?
I would say if you want to change the value of a static variable inside fn
between calls to fn
example (untested)

int& fn(int arg)
{
static int persist = 2;

// so some work here

return persist;
}

int main()
{
fn(1); // persist == 2 after this call
fn(2) = 7; // persist will be 7 after this
fn(3); // persist is still 7

return 0;
}

Thanks!!!
Dan
 
R

Rolf Magnus

Dan said:
according to the body of fn, you may get an overflow. otherwise the
statement above will initialise y with 5

Actually, the behavior will be undefined, because the value of an
uninitialized variable is used (within the function). That happens before
the assignment.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,241
Latest member
Lisa1997

Latest Threads

Top