Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a dummy lvalue that can be used when nothing is to be executed?

Consider the following C99 function:

void port_pin_set(const bool value, const uint8_t pin_mask)
{
    if (value) {
        PORT |= pin_mask;
    } else {
        PORT &= ~pin_mask;
    }
}

With PORT being a define, for example:

#define PORT (P1OUT)

Is there a way to redefine PORT so that:

  • it is accepted as an lvalue,
  • the function does not do anything.

What I want to do is to keep the function source as is, while compiling it to do nothing.

Edit: I am aware that using such an lvalue might not be the best solution. I am not looking for the best solution for this specific problem, I am interested in the language itself. This is a theoretical question, not a pragmatic one.

like image 347
Gauthier Avatar asked Jan 17 '12 14:01

Gauthier


3 Answers

C99 has compound literals that can be used for such a task. Their syntax is a cast followed by an initializer:

#define PORT ((int){0})

should do it in your case, only that you might get some warnings about unused values or so.

Any decent compiler will optimize assignments to such compound literal out.

like image 187
Jens Gustedt Avatar answered Nov 15 '22 06:11

Jens Gustedt


You can define a variable of the same type as your P1OUT (say, unsigned char), make it available in the header, and define it in one of the sources, like this:

Header:

extern unsigned char dummy_P1OUT;
#define PORT (dummy_P1OUT)

C file:

unsigned char dummy_P1OUT;

Usages:

PORT &= ~pin_mask;

if (PORT & pin_mask) {
    blink_led();
}
like image 23
Sergey Kalinichenko Avatar answered Nov 15 '22 06:11

Sergey Kalinichenko


This should do it in C99:

#ifdef PORT
#undef PORT
#endif

#define PORT int x = 0; x

for your case. But I suggest you put the whole code between #ifdef's instead of redefining PORT:

void port_pin_set(const bool value, const uint8_t pin_mask)
{
#ifdef BUILD_PORT_PIN_SET
    if (value) {
        PORT |= pin_mask;
    } else {
        PORT &= ~pin_mask;
    }
#endif
}
like image 29
Luchian Grigore Avatar answered Nov 15 '22 06:11

Luchian Grigore