Returning a structure without initializing it

I have a very simple color structure like

struct {
    unsigned char red;
    unsigned char green;
    unsigned char blue;
    unsigned char alpha;
} RGBA;

Now in some function I would like to return such a structure.

But I can’t figure out how to do this. All I can imagine is to create a local structure by filling out each field separately and then returning it.

RGBA localStructure;
localStructure.red = r;
localStructure.green = g;
localStructure.blue = b;
localStructure.alpha = a;
return localStructure;

Where I really would like to do something like this

return RGBA(r,g,b,a);

Is there a way to achieve this in C / C ++?

+3
source share
8 answers

First, in your first fragment, RGBA is an object whose type is an unnamed structure. I do not think you intended. You probably meant:

typedef struct { ... } RGBA; /* what a lot of C programmers do */

or

struct RGBA { ... }; /* probably what you meant */

In any case, to answer your question, give it a constructor!

struct RGBA {
    RGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a) : red(r), green(g), blue(b), alpha(a) {
    }

    unsigned char red;
    unsigned char green;
    unsigned char blue;
    unsigned char alpha;
};

Then you can write:

return RGBA(r,g,b,a);
+7
source

C :

RGBA x = { r, g, b, a };

, , , :

return (RGBA) { r, g, b, a };
+3

++ .

struct RGBA{
    unsigned char red;
    unsigned char green;
    unsigned char blue;
    unsigned char alpha;

    RGBA( unsigned char _red, unsigned char _green, unsigned char _blue, unsigned char _alpha ) : red( _red ), green( _green ), blue( _blue ), alpha( _alpha )
    {}

};
+3

struct { ... } RGBA RGBA . , typedef struct { ... } RGBA;. :

RGBA fun() {
    RGBA obj = { 0xff, 0xff, 0xff, 0 };
    return obj;
}

GCC C99 C90 ++, :

RGBA fun() {
    return ((RGBA){ 0xff, 0xff, 0xff, 0 });
}
+2

, .

struct RGBA { 

   RGBA(unsigned char r, unsigned char g, unsigned b, unsigned char a = 0xff)
     : red(r)
     , green(g)
     , blue(b)
     , alpha(a)
   {
   }

   ...
};

:

 RGBA t = RGBA(0xff,0xff,0);

 return RGBA(0,0,0,0xff);

: - ++. ++. .

+1

, RGBA , . C, ++, :

struct RGBAInitialisor
{
    RGBAInitialisor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
        impl_.alpha = a;
        impl_.blue = b;
        impl_.green = g;
        impl_.red = r;
    }
    // This converts back to the RGBA on the fly.
    operator RGBA ()
    {
        return impl_;
    }
    RGBA impl_;

};

RGBA f()
{
    return RGBAInitialisor(1,2,3,4);
}
+1

struct ( struct) 4 .

0

++ - , , .

C , , ,

RGBA localStructure;
memset(&localStructure, 0, sizeof(localStructure));
0

Source: https://habr.com/ru/post/1792246/


All Articles