What does this mean?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Protoman

    What does this mean?

    What does this do?

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

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

  • Dan Cernat

    #2
    Re: What does this mean?

    See below

    "Protoman" <Protoman2050@g mail.com> wrote in message
    news:1134267381 .114631.110770@ g43g2000cwa.goo glegroups.com.. .[color=blue]
    > What does this do?
    >
    > int& fn(int& arg){arg++;retu rn arg;}
    > //later
    > int y;
    > fn(y)=5; <-- use of uninitialised variable y[/color]
    according to the body of fn, you may get an overflow. otherwise the
    statement above will initialise y with 5
    [color=blue]
    >
    > Why can you do it?[/color]
    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!!![color=blue]
    >[/color]

    Dan


    Comment

    • Rolf Magnus

      #3
      Re: What does this mean?

      Dan Cernat wrote:
      [color=blue]
      > "Protoman" <Protoman2050@g mail.com> wrote in message
      > news:1134267381 .114631.110770@ g43g2000cwa.goo glegroups.com.. .[color=green]
      >> What does this do?
      >>
      >> int& fn(int& arg){arg++;retu rn arg;}
      >> //later
      >> int y;
      >> fn(y)=5; <-- use of uninitialised variable y[/color]
      > according to the body of fn, you may get an overflow. otherwise the
      > statement above will initialise y with 5[/color]

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

      Comment

      Working...