Home > Back-end >  How can I assign a const unsigned char value to a variable inside a condition in c ?
How can I assign a const unsigned char value to a variable inside a condition in c ?

Time:07-22

I am using C for programming a microcontroller, and I have this situation.

I have several const unsigned char in a .h file. Ex:

const unsigned char epd_bitmap_icon1 [] = {...
const unsigned char epd_bitmap_icon2 [] = {...

I have a function that takes one of this variables:

void drawBitmap(int16_t x, int16_t y, uint8_t *bitmap, int16_t w, int16_t h, uint16_t color);

In this case, I need to conditionally pass a different bitmap based on a certain value.

In python would be something like this:

if value > 80:
    icon = epd_bitmap_icon1
elif value > 30:
    icon = epd_bitmap_icon2
else:
    icon = edp_bitmap_icon3

and later pass the icon value to drawBitmap as the third argument.

I don't know how to do it in C , I have tried this:

    if (batteryChargePercent > 80) {
        unsigned char* icon = epd_bitmap_icon1;
    }
    else if (batteryChargePercent > 30) {
        unsigned char* icon = epd_bitmap_icon2;

    } else {
        unsigned char* icon = epd_bitmap_icon3;
    }

But I get this error:

error: invalid conversion from 'const unsigned char*' to 'unsigned char*' [-fpermissive]

CodePudding user response:

Declare the variable once outside the if, and assign it in the if.

const unsigned char *icon;
if (batteryChargePercent > 80) {
    icon = epd_bitmap_icon1;
} else if (batteryChargePercent > 30) {
    icon = epd_bitmap_icon2;
} else {
    icon = epd_bitmap_icon3;
}

You need to use const in the pointer declaration to solve the error message.

CodePudding user response:

You can either use a ternary, for simple cases:


const unsigned char* icon = batteryChargePercent > 80 ? epd_bitmap_icon1 :
                      batteryChargePercent > 30 ? epd_bitmap_icon2 :
                                                  epd_bitmap_icon3;

or, if it's more complicated, you might use a lambda that's called on-the-spot:

const unsigned char* icon = [&]() {
    if (batteryChargePercent > 80) {
        return epd_bitmap_icon1;
    }
    else if (batteryChargePercent > 30) {
        return epd_bitmap_icon2;
    } else {
        return epd_bitmap_icon3;
    }
}();

Also, while not yet standard, statement expressions might help you:

const unsigned char* icon = ({
    const unsigned char* retval;
    if (batteryChargePercent > 80) {
        retval = epd_bitmap_icon1;
    }
    else if (batteryChargePercent > 30) {
        retval = epd_bitmap_icon2;
    } else {
        retval = epd_bitmap_icon3;
    }
    retval;
});
  • Related