Reputation: 73
After compiling my C code with -Wall activated, the following warnings appeared
left operand of comma operator has no effect
which are related with the the multiple arguments presented in my return
statements. The story is the following:
Assume to have a bunch of dynamically allocated 3D arrays (A,B and C) and want to do some manipulation on them. The arrays are defined as pointer to pointer to pointer and allocated using malloc (the standard procedure). The manipulation of them will occur in seperate functions. For some reason I declare the function as a triple pointer and as follow:
***func( double ***A, double ***B, double ***C)
{
do some work here on A, B and C
return(A, B, C);
}
I know that the arrays are passing into the function as reference so essentially there is no need of returning something from this function. But, can you tell me why someone would declare a function this way. This staff confuses me. Thanks in advance
Upvotes: 2
Views: 145
Reputation: 40655
The code
***func( double ***A, double ***B, double ***C)
{
do some work here on A, B and C
return(A, B, C);
}
is simply wrong, even though it compiles:
If the function returns everything via its arguments A
, B
, and C
, it should not have a return type. I. e., it should be declared to return void
:
void func( double ***A, double ***B, double ***C) {
The syntax return(A, B, C)
does not do what you think it does. It does not construct a list, or pass three values to return
. Instead, it evaluates the expression A
, throws its value away, evaluates B
, throws its value away, evaluates C
, takes the value of C
as the value of the expression (A, B, C)
, and finally returns that value from the function. (Google "C comma operator" for more information.)
If your function is declared as returning void
(as it probably should be), there is simply no need for a return
statement.
Upvotes: 0
Reputation: 18009
, you can use a return(A, B, C) is not C
struct
to return more than one arguments.
struct array3d{
double* A;
double* B;
double* C;
};
struct array3d* func(struct array3d* p) {
/* do some work here on p->A, p->B and p->C */
return p;
}
Here is an working example with ***
pointers:
#include <stdio.h>
#include <malloc.h>
struct array3d {
double*** A;
double*** B;
double*** C;
};
struct array3d* func(struct array3d* p) {
/* do some work here on A, B and C */
***p->A /= 42.0;
***p->B /= 42.0;
***p->C /= 42.0;
return p;
}
int main()
{
struct array3d arr;
struct array3d* p_arr;
double A[] = { 1.0, 3.0}; // ...
double B[] = {-1.0, -2.0};
double C[] = { 2.0, 4.0};
double* p1A = A;
double* p1B = B;
double* p1C = C;
double** p2A = &p1A;
double** p2B = &p1B;
double** p2C = &p1C;
arr.A = &p2A;
arr.B = &p2B;
arr.C = &p2C;
p_arr = func(&arr);
printf("(A = %f, B = %f, C = %f)\n", ***p_arr->A, ***p_arr->B, ***p_arr->C);
return 0;
}
Upvotes: 5