delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/04/18/13:58:07

Date: Sat, 18 Apr 1998 10:52:17 -0700 (PDT)
From: Nate Eldredge <nate AT cartsys DOT com>
To: "Jeff W./DMT" <dmt AT bigfoot DOT com>
cc: djgpp AT delorie DOT com
Subject: Re: Linked Lists?
In-Reply-To: <35384655.75520@news.ziplink.net>
Message-ID: <Pine.LNX.3.96.980418104517.259B-100000@unixbox.bitbucket.org>
MIME-Version: 1.0

On Sat, 18 Apr 1998, Jeff W./DMT wrote:

> I know how to write one in Pascal, but I'm having some trouble in C++.
> My basic problem is that I have a function, InsertNode(ListNode *List,
> i) that adds a new node with data value I to the end of a current
> list.  Here is the code:
[expunged]
> 
> Everything works fine, however, when the function exits, the variable
> that I had originally passed to InsertNode remains unchanged.  How
> would I do this??
>  --Jeff W.

That's because of the difference between passing arguments by value and
passing by reference.  Passing by value creates a local copy of the value
for the function, while by reference actually passes the address of the
variable, so it can be modified.  C has no way to pass by reference
automatically (though I think C++ does-- read on), so you have to do it
explicitly. This Pascal code (which may be wrong, my Pascal is rusty):

Procedure ChangeToFive (var x : integer);
begin
  x := 5;
end;

(* in another function *)
var y : integer;
ChangeToFive(y);

would have to be written like this in C:

void change_to_five(int *x) /* Note that x is a *pointer* to int */
{
  *x = 5;
}

int y;
change_to_five(&y); /* Here you pass the address */

But I think in C++ you can do it like this:

void change_to_five(int& x)
{
  x = 5;
}

int y;
change_to_five(y);

I hope somebody will correct me if I'm wrong.

Nate Eldredge
nate AT cartsys DOT com

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019