Search code examples
cstructassignment-operator

How to assign the same value to multiple members in a struct in C


I was wondering if there was a more concise way to assign the same variable to multiple members of the same struct?

Currently my code looks like this:

                image[i][j].rgbtBlue = average;
                image[i][j].rgbtGreen = average;
                image[i][j].rgbtRed = average;

It just seems like a lot of repitition. I don't want to alter the struct in any way I just wondered if there is any way I can make the above code more neat? But here is the code for the struct anyway.

typedef struct
{
    BYTE  rgbtBlue;
    BYTE  rgbtGreen;
    BYTE  rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

TIA


Solution

  • One way would be

    image[i][j].rgbtBlue = image[i][j].rgbtGreen = image[i][j].rgbtRed = average;
    

    If you're getting tired of typing "image[i][j]", and you're doing a lot with it in the same stretch of code, you could set up a temporary variable:

    RGBTRIPLE *trip = &image[i][j];
    
    trip->rgbtBlue = trip->rgbtGreen = trip->rgbtRed = average;
    

    Setting up a temporary variable like this has some pros and cons:

    • Pro: it saves typing
    • Con: but saving typing isn't really a goal, you only type it once
    • Pro: it can be easier to read
    • Con: if you're not careful (if i or j changes when you don't expect), it can introduce bugs