A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
In C++, a function can return only a single value (its declared return type), and arguments are passed by value by default. The code in the example does not modify the caller’s variables because:
- The parameters
arg1,arg2,arg3are copies ofAA,BB,CC. -
return(arg1, arg2, arg3);uses the comma operator. In C and C++, the comma operator evaluates all expressions but the result of the whole expression is the value of the last operand. So this is equivalent toreturn arg3;. - The function is declared as
float values(arg1, arg2, arg3), so it returns a singlefloat(the value ofarg3), and it does not assign anything back intoAA,BB,CC. - The call
values(AA, BB, CC);ignores the single returnedfloatvalue, soAA,BB,CCremain unchanged at 0.
To achieve the intended behavior (have the function write into AA, BB, CC), use one of these approaches:
1. Pass by reference (C++)
void values(float& arg1, float& arg2, float& arg3)
{
arg1 = 2.0f;
arg2 = 3.0f;
arg3 = 4.0f;
}
int main()
{
float AA = 0.0f;
float BB = 0.0f;
float CC = 0.0f;
values(AA, BB, CC);
// Now AA == 2, BB == 3, CC == 4
}
2. Return a struct or class (C++)
struct Values {
float a;
float b;
float c;
};
Values values()
{
return {2.0f, 3.0f, 4.0f};
}
int main()
{
Values v = values();
float AA = v.a;
float BB = v.b;
float CC = v.c;
}
3. Use out parameters (C style, via pointers)
void values(float* arg1, float* arg2, float* arg3)
{
*arg1 = 2.0f;
*arg2 = 3.0f;
*arg3 = 4.0f;
}
int main()
{
float AA = 0.0f;
float BB = 0.0f;
float CC = 0.0f;
values(&AA, &BB, &CC);
}
The key points from the language rules are:
- Function arguments are passed by value unless explicitly passed by reference or pointer.
- A function returns exactly one value, of its declared return type.
-
return (a, b, c);returns onlycbecause of the comma operator semantics.
References: