Mailing List Archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] Getting back into C programming



On 06/12/06, burlingk@example.com <burlingk@example.com> wrote:

void func(int &a){a++; return;}

For instance would take an integer without any special  notation and
increment it.

The reference operator is really syntactic sugar more than anything. It allows you to use a parameter variable normally (i.e. without dereferencing it) in your function body, but without having to pay the price of pass-by-value.

Your function is exactly equivalent to:

void func(int *const a) { (*a)++; return; }

void func(int * a) {a++; return;}
Theoretically does the same thing, but wants either a pointer to an int,
or an integer specifically notated as &a.

No, this theoretically performs pointer arithmetic. :) See my example above, then compile and run this code that illustrates what your example really does:

==

#include <stdio.h>

void func(int * a) {
/*** DEBUGGERY ***/
 fprintf(stderr, "(0x%x) %d\n", (unsigned)a, *a);
/*** DEBUGGERY ***/
 a++;
/*** DEBUGGERY ***/
 fprintf(stderr, "(0x%x) %d\n", (unsigned)a, *a);
/*** DEBUGGERY ***/
 return;
}

int main(void) {
 int foo = 0;
 func(&foo);
 return 0;
}

==

Just in case you don't have a C compiler handy:

: jglover@example.com; gcc -g -Wall -o func func.c
: jglover@example.com; ./func
(0xbfffc3e4) 0
(0xbfffc3e8) -1073757176

Of course my logic is based more off of C++.

Note that:

void func(int &a){a++; return;}

will *only* work in C++. In C, the only meaning of '&' is "address
of", and it will not work in a function prototype:

: jglover@example.com; grep '^void func' func.c
void func(int &a){a++; return;}
: jglover@example.com; gcc -g -Wall -o func func.c
func.c:3: error: syntax error before '&' token
func.c: In function `func':
func.c:4: error: `a' undeclared (first use in this function)
func.c:4: error: (Each undeclared identifier is reported only once
func.c:4: error: for each function it appears in.)

-Josh


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links