This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: naming results in C?
- To: "Martin v. Loewis" <martin at mira dot isdn dot cs dot tu-berlin dot de>
- Subject: Re: naming results in C?
- From: Patrik Hagglund <patha at ida dot liu dot se>
- Date: Sat, 27 Mar 1999 17:53:19 +0100
- cc: egcs at egcs dot cygnus dot com, patha at ida dot liu dot se
> In C++, copying into the result often has significant costs
> (copying constructor), which is reduced with that extension. For
> C, no such need exists.
Yes, that's what the documentation tells you. :)
I thought of using it for returning arrays. Take the following
example program in C, where mult_v multiplies a vector with a
scalar (using variable length arrays):
/* printf */
#include <stdio.h>
void
print_v(int n, double v[]) {
int i;
for (i = 0; i < n; i++)
printf("%g ", v[i]);
printf("\n");
}
void
init_v(int n, double v[]) {
int i;
for (i = 0; i < n; i++)
v[i] = i;
}
/* multipy vector v with float f */
void
mult_v(double f, int n, double v[], double res[]) {
int i;
for (i = 0; i < n; i++)
res[i] = f * v[i];
}
/* atoi */
#include <stdlib.h>
int
main(int argc, char **argv) {
int n = atoi(argv[1]);
double v1[n], v2[n], v3[n];
init_v(n, v1);
print_v(n, v1);
mult_v(2.0, n, v1, v2);
mult_v(3.0, n, v2, v3);
print_v(n, v3);
return 0;
}
The array v1 is multiplied two times and the final result is
stored in v3.
Now, if I was able to declare mult_v like (this is impossible with
the current C++ extension):
mult_v(double f, int n, double v[]) return double res[n]
then it would be possible to use mult_v like:
double *v3;
v3 = mult_v(3.0, n, mult_v(2.0, n, v1));
There have to be many situations in C (not just C++) where you
want to contruct operator-like functions (operating on objects
with non-trivial size) instead of passing a reference to the
result variable.
BTW, I think that using a result variable is more intuitive than
using a return statement (it is more symmetric).
Regards,
Patrik Hägglund