Re: Passing by reference

From: Peter Ajamian (peter@pajamian.dhs.org)
Date: 03/13/01


Kras Kresh wrote:
>
> Is passing by reference even possible on circle?

Note that this is really a question about C in general rather than
CircleMUD in particular.  The post would be much more on-topic in a
newsgroup such as alt.comp.lang.learn.c-c++, however, I'll answer it for
you here anyways:

You cannot pass a reference in C as you can in C++, however there are
other ways to accomplish the exact same thing by passing pointers
instead.  I'll give an example here:

#include <stdlib.h>

/*
 * This function will increment the integer passed to it.
 */
void int_incr(int *i)
{
  *i++;
}

int main(void)
{
  int j=0, k=0;

  printf("j = %d, k = %d\n", j, k);
  int_incr(&j);
  printf("j = %d, k = %d\n", j, k);
  return 0;
}

The output of the above program will be this...
j = 0, k = 0
j = 1, k = 0

Thus you can see that the int_incr function actually changed the value of
j.

Now if you want to make it look a little more (but not entirely)
C++-like, you can use macros to make it so that you don't have to
reference j when passing it, or dereference it in the function, something
like this...

#include <stdlib.h>

/*
 * This function will increment it's argument.
 */
#define i (*_i)
int int_incr_f(int i)
{
  i++;
}
#undef i
#define int_incr(i) int_incr_f(&(i))

int main(void)
{
  int j=0, k=0;

  printf("j=%d, k=%d\n", j, k);
  int_incr(j);
  printf("j=%d, k=%d\n", j, k);
  return 0;
}

This program will also output the same as the prior one:
j=0, k=0
j=1, k=0

What's happening here is you're actually using the pre-processor to
substitute &j for j in the function call and to substitute *i for i
inside the int_incr function.  After running your code through the
preprocessor it will look very much like that in the first example.

Regards, Peter

--
   +---------------------------------------------------------------+
   | FAQ: http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html |
   | Archives: http://post.queensu.ca/listserv/wwwarch/circle.html |
   +---------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/04/01 PST