Passing a reference to a value returned by a function

Oliver Kullmann O.Kullmann@Swansea.ac.uk
Tue Mar 11 16:23:00 GMT 2003


On Tue, Mar 11, 2003 at 05:56:34PM +0200, Mihnea Balta wrote:
> Mailing-List: contact gcc-help-help@gcc.gnu.org; run by ezmlm
> Precedence: bulk
> List-Unsubscribe: <mailto:gcc-help-unsubscribe-O.Kullmann=swansea.ac.uk@gcc.gnu.org>
> List-Archive: <http://gcc.gnu.org/ml/gcc-help/>
> List-Post: <mailto:gcc-help@gcc.gnu.org>
> List-Help: <mailto:gcc-help-help@gcc.gnu.org>
> Delivered-To: mailing list gcc-help@gcc.gnu.org
> From: Mihnea Balta <dark_lkml@mymail.ro>
> To: gcc-help@gcc.gnu.org
> Date: Tue, 11 Mar 2003 17:56:34 +0200
> Subject: Passing a reference to a value returned by a function
> X-Spam-Status: No, hits=0.0 required=8.0
> 	tests=none
> 	version=2.50
> X-Spam-Level: 
> X-Spam-Checker-Version: SpamAssassin 2.50 (1.173-2003-02-20-exp)
> X-MIME-Autoconverted: from quoted-printable to 8bit by cs-svr1.swan.ac.uk id h2BFw0uE014171
> 
> Hi.
> 
> I have this piece of code (excuse the long function names, it's example code 
> :) ):
> 
> #include <stdio.h>
> 
> struct type_t{
>     int a, b, c;
> };
> 
> type_t function_returning_struct(){
>     type_t  a;
> 
>     a.a = 1;
>     return a;
> }
> 
> int function_taking_reference(type_t& a){
>     if(a.a == 1)
>         return 1;
>     else
>         return 0;
> }
> 
> int main(){
>     printf("%d\n", function_taking_reference(function_returning_struct()));
>     return 1;
> }
> 
> I'm trying to port code written like this from visualc to gcc. I suppose that 
> visualc compiles the above piece of code because it creates a temporary 
> type_t that holds the return of function_returning_struct(), and passes a 
> reference to that to function_taking_reference(). However, gcc 3.2.2 won't 
> compile that kind of code.
> 
> Is there any way to make gcc work with such code? I'm asking because it's in a 
> lot of places, and adding a temp var by hand to all the places where this 
> stuff occurs would be a pain.
> 
> Thanks.

Hi,

I hope very much that there is no way to make gcc to work with such code,
since it doesn't make sense to pass temporary values by reference, and the
standards explicitely forbids it. But you don't have to add variables ---
just add the const qualifier to the argument type of function_taking_reference,
and you have perfectly legal C++ code. Doing so doesn't change your code,
but just increases safety.

Oliver



More information about the Gcc-help mailing list