Why do I need this strange cast for enum arithmetics? - c

I have this piece of code:
typedef enum myEnum_e
{
VAL0,
VAL1
} myEnum;
void func(void)
{
myEnum val = (myEnum) 0;
while(/*Do something*/)
{
val = val + ((myEnum)1); // <= Warning here
}
}
This piece of code produces the warning:
enumerated type mixed with another type
To clean this I ended up with:
void func(void)
{
myEnum val = (myEnum) 0;
while(/*Do something*/)
{
val = ((myEnum) val + 1); // <= NO Warning here
}
}
Could someone tell why the first form is incorrect?
I feel like the second is less meaningful than the first one.
I mean I would prefer to read:
Add 1, considered as a myEnum value, to val (and store the result in val)
Than
Store in val val + 1 considered as a myEnum value
Note: This is a TI C28x compiler (for TI C2000 MCUs).
Edit:
My real application is to define a custom UART communication for embedded software.
So here is what I have done:
typedef enum e_frame
{
FRAME_A,
FRAME_B,
FRAME_C,
FRAME_COUNT
} frame_e;
typedef enum e_frameId
{
FRAMEID_A = 0x0A,
FRAMEID_B = 0x42,
FRAMEID_C = 0xFF
} frameId_e;
const frameInfo_s FramesInfo[FRAME_COUNT] =
{
[FRAME_A] =
{
.id = MCM_FRAMEID_A,
// And other stuff
},
[FRAME_B] =
{
.id = MCM_FRAMEID_B,
// And other stuff
},
[FRAME_C] =
{
.id = MCM_FRAMEID_C,
// And other stuff
}
}
Finally the the ID to frame_e function:
frame_e UAR_FrameId2Frame(frameId_e id)
{
frame_e frame = (frame_e) 0;
while(FramesInfo[frame].id != id && frame < FRAME_COUNT)
{
frame = (MCM_frames_e)(frame + 1);
}
return frame;
}

I don't get any warnings here:
#include <stdio.h>
typedef enum myEnum_e
{
VAL0,
VAL1
} myEnum;
int main (int argc, char *argv[]) {
myEnum val = 0;
while( 1 /*Do something*/)
{
val = val + 1;
}
return 0;
}
Compiler: GCC 4.2.1
Compile command: gcc -Wall -pedantic x.c

It's a good thing that you are getting a warning.C is not a strictly typed language so you don't get errors when mixing types that can be coerced into one another. But mixing types has the potential to cause subtle runtime errors. So, although internally enums and integers are same types, you shouldn't be mixing them. You should consider using an enum increment variable initialized to 1.

First of all, having code with a lot of casts is not very pleasant to read, but well, that's just a matter of taste.
If you plan to do arithmetic you might want to explicitly define values for the enums. It's risky to do this anyway, because you could end up with an out-of-range values.
What if you add 3 to your VAL0?
Think about it, what does that mean? You've declared an enum, but the value that you now got is not a valid enum anymore. The reason to use an enum is mostly that you want to limit the number of possible values for an ordinal.
In your situation it makes more sense to have constants like VAL0 and VAL1.
Or, if all you needed was to iterate over your enum, you could do this:
typedef enum myEnum_e
{
VAL0,
VAL1,
// ...
VAL66
} myEnum;
for(int i=VAL0; i<=VAL66; i++) {
// do something here
}

Related

using function names as functions in a C macro

Suppose i have code like this in my program:
if (!strcmp(current, "sin")) {
pushFloat(sin(x), &operands);
} else if (!strcmp(current, "cos")) {
pushFloat(cos(x), &operands);
} else if (!strcmp(current, "tan")) {
pushFloat(tan(x), &operands);
} else if (!strcmp(current, "ctg")) {
pushFloat(1. / tan(x), &operands);
} else if (!strcmp(current, "ln")) {
pushFloat(log(x), &operands);
} else if (!strcmp(current, "sqrt")) {
pushFloat(sqrt(x), &operands);
}
There are function names such as "sin" or "cos" saved in the current char array
Instead of using this long if block, or replacing it with an even longer switch block, i wanted to write a simple macro like this: #define PUSHFUNC(stack, func, value)(pushFloat(func(value), &stack)) and call it like this PUSHFUNC(operands, current, x)
Doing it this way creates an error "current is not a function or function pointer". I initially thought macros are just text replacement, so if i force a string that is equal to an actual function into a macro, it would expand to the function itself, but looks like i was wrong. Is there a way to achieve what i want using a macro, or should i just write a map block?
I initially thought macros are just text replacement,
That's your problem: macros are just text replacement. So if you have:
#define PUSHFUNC(stack, func, value) (pushFloat(func(value), &stack))
And you write:
PUSHFUNC(operands, current, x)
You get:
(pushFloat(current(value), &operands))
And indeed, you have no function named current. Macros are expanded before your code compiles; the preprocessor has no knowledge of the content of your variables.
If you really want to avoid a long chain of if statements, you could implement some sort of table lookup:
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <math.h>
typedef double (*floatop)(double x);
typedef struct {
char *name;
floatop operation;
} entry;
double ctg(double);
entry opertable[] = {
{"sin", sin},
{"cos", cos},
{"tan", tan},
{"ctg", ctg},
{"sqrt", sqrt},
{NULL, NULL},
};
double ctg(double x) {
return 1. / tan(x);
}
floatop findop(char *name) {
int i;
for (i=0; opertable[i].name; i++) {
if (strcmp(opertable[i].name, name) == 0) {
return opertable[i].operation;
}
}
}
int main() {
float x = 4;
printf("sin(%f) = %f\n", x, findop("sin")(x));
printf("sqrt(%f) = %f\n", x, findop("sqrt")(x));
printf("tan(%f) = %f\n", x, findop("tan")(x));
printf("ctg(%f) = %f\n", x, findop("ctg")(x));
}
...but this requires that all of your functions take the same arguments, so for things like ctg you would need to add a helper function. You also need to decide if the increased complexity of the table lookup makes sense: it really depends on how many different operation names you expect to implement.
The output of the above code is:
sin(4.000000) = -0.756802
sqrt(4.000000) = 2.000000
tan(4.000000) = 1.157821
ctg(4.000000) = 0.863691
Is there a way to achieve what i want using a macro, or should i just write a map block?
I would recommend using an enum containing symbols for all the functions you might want to call, and using that in a switch-case block, instead of comparing a bunch of strings. Here's a very brief sample that only uses some of the functions you refer to...
enum which_func { SIN, COS, TAN, };
enum which_func which = SIN;
switch (which) {
case SIN:
pushFloat(sin(x), &operands);
break;
case COS:
pushFloat(cos(x), &operands);
break;
case TAN:
pushFloat(tan(x), &operands);
break;
default:
assert(false); // shouldn't be reachable if enum value is well-defined
}
This version will be easier to maintain in the long run, more efficient to execute and possibly more robust to logic errors (there are some compiler warnings that you can enable which will warn you if you're not handling all enum values, which can help you catch missed cases in your logic).
To add to what other answers said, what you can do is to make a macro that expands to the "basic block" of your if chain, avoiding some repetitions thanks to the stringizing operator:
#define HANDLE_FN_EXPR(fn, expr) \
else if(!strcmp(current, #fn)) \
pushFloat((expr), &operands)
#define HANDLE_FN(fn) \
HANDLE_FN_EXPR(fn, fn(x))
Then you can do
if(0);
HANDLE_FN(sin);
HANDLE_FN(cos);
HANDLE_FN(tan);
HANDLE_FN_EXPR(ctg, 1./tan(x));
HANDLE_FN(ln);
HANDLE_FN(sqrt);
Macros do in fact do text replacement. Given your macro definition, this:
PUSHFUNC(operands, current, x)
expands to this:
(pushFloat(current(x), &operands))
So as you can see, the text that is being replaced is the name of the variable, not the text that it contains.
And even if this did work as you expected, it wouldn't be able to properly handle the 1. / tan(x) case.
This means there isn't really a better way to do what you want.
Why not create some objects for each function type? I know, this is C not C++, but the idea will still work. First, create the function object type:-
typedef struct _Function
{
char *name;
float (*function) (float argument);
} Function;arg
And now create an array of function objects:-
Function functions [] =
{
{ "sin", sin },
{ "cos", cos }
// and so on
};
where the functions are defined:-
float sin(float x)
{
return 0; // put correct code here
}
float cos(float x)
{
return 0; // put correct code here
}
Finally, parse the input:-
for (int i = 0; i < sizeof functions / sizeof functions[0]; ++i)
{
if (strcmp(functions[i].name, current) == 0)
{
pushFloat(functions[i].function(arg)); // add operands!
break;
}
}
I find using enums for stuff like this very hard to maintain! Adding new functions means going through the code to find cases where the enum is used and updating it prone to errors (like missing a place!).
All because it's not C++, doesn't mean you can't use objects! It's just there's no language support for it so you have to do a bit more work (and, yeah, there are features missing!)

Computing enum "string" from the value

So I have the following enum and I have some states in each of which I want to print the STATUS instance based on event_id. So is there a way to compute the enum "string" from its value?
typedef enum {
WIFI_START,
WIFI_DIS,
WIFI_CON
} STATUS;
void eventHandler(int event_id)
{
if (event_id == WIFI_START) {
// ...
printf ("WIFI_START is triggered");
}
...
}
The least-clever approach is to allocate some string constants that line up with the enumeration and index into it using the enumeration:
#include <stdio.h>
typedef enum {
WIFI_START,
WIFI_DIS,
WIFI_CON
} STATUS;
const char *status[] = {"WIFI_START", "WIFI_DIS", "WIFI_CON"};
void eventHandler(int event_id) {
printf("%s is triggered", status[event_id]);
}
int main() {
eventHandler(WIFI_DIS);
return 0;
}
I prefer this over a macro because, debugging/development utilities aside, program logic should be decoupled from the names used by the program to represent data. In other words, the program shouldn't behave differently based on variable name characteristics; it should be possible to minify, obfuscate or refactor the source code and be guaranteed you'll still get the same output.

C Unit Test: stub a constant structure (gcc --wrap)

Hi All here is my specific case:
service.h:
typedef struct {
uint8_t (*function1)(void);
uint8_t (*function2)(void);
} const service_struct_t;
extern service_struct_t service_api ;
service.c:
#include "service.h"
static uint8_t foo(void){
return 13+6;
}
static uint8_t bar(void){
return 7*6;
}
service_struct_t service_api = {
.function1 = foo,
.function2 = bar,
};
I need to stub (to mock, to replace) these functions but I have no right to change that original code. I'm using gcc to compile the unit tests. I've failed to:
use the --wrap option of gcc straight on foo and bar since they are static to source.c :
#include "service.h"
#define ENABLE_STUB 1 /* that is actually a variable toggled at runtime */
uint8_t __real_foo(void);
uint8_t __wrap_foo(void){
if(ENABLE_STUB){
return 1;
}else{
return __real_foo();
}
}
/* same for bar */
use the --wrap option of gcc onto the service_api object symbol because it's not a function
#include "service.h"
#define ENABLE_STUB 1 /* that is actually a variable toggled at runtime */
uint8_t __real_service_api ;
uint8_t __wrap_service_api = {
.function1 = foo,
.function2 = bar,
}
static uint8_t foo(void){
if(ENABLE_STUB){
return 1;
}else{
return __real_service_api.function1();
}
}
/* same for bar */
simply reassign the service_api member functions since the structure is constant and already assigned.
#include "service.h"
#define ENABLE_STUB 1 /* that is actually a variable toggled at runtime */
service_struct_t backup_service_api = {
.function1 = service_api.function1;
.function2 = service_api.function2;
}
service_struct_t stub_service_api = {
.function1 = foo;
.function2 = bar;
}
uint8_t foo(void){
if(ENABLE_STUB){
return 1;
}else{
return __real_foo();
}
}/* same for bar */
void service_poke_stub(bool_t enable_stubs){
if(enable_stubs){
service_api.function1 = stub_service_api.function1
service_api.function2 = stub_service_api.function2
}else{
service_api.function1 = backup_service_api.function1
service_api.function2 = backup_service_api.function2
}
}
thanks already for your help
You can't mock the functions in the structure, as you already found out.
So it depends on what you like to test:
If you want to test whether the structure contains the correct functions, the module service.c is your module-under-test and should be used as is. You need to check the correctness by watching what is done by the functions.
If you want to test that the structure is used correctly, you will mock the whole module. Now you are free to put in it whatever you want.
If your source code does not allow this, the design is bad for testing. This is often the case when the architecture is not done with testability in mind.

How to create derived structure properties in C

In Python, its possible to create a derived property from a class using the #property decorator for example
class State():
def __init__(self, fav_num_monday, fav_num_not_monday, is_monday):
self.fav_num_monday = fav_num_monday
self.fav_num_not_monday = fav_num_not_monday
self.is_monday = is_monday
#property
def fav_num(self):
return self.is_monday * self.fav_num_monday + \
(1 - self.is_monday) * self.fav_num_not_monday
state = State(12, 5, 0)
print("Current favourite number: %d" % state.fav_num)
My question is then what is the best way to achieve this in C (where speed is of the utmost importance). I've have added below some ways I have tried but am not sure if they could have repercussions in a larger codebase. They are as follows:
Simply writing out the whole expression each time.
Pros: No unexpected repercussions, no code/speed penalty.
Cons: Ugly code, takes a long time to write.
Using a get function.
Pros: Code easier to read.
Cons: Inefficient code (slower than 1).
Defining a macro.
Pros: No code/speed penalty. Code quick to write.
Cons: Potential repercussions later, code not so easy to follow.
The example program is below
#include <stdio.h>
#include <string.h>
#define state_fav_num state.is_monday * state.fav_num_monday + (1 - state.is_monday) * state.fav_num_not_monday
struct State {
int fav_num_monday;
int fav_num_not_monday;
int is_monday;
};
int get_state(struct State *state, char *property) {
// Returns value of the property in state.
// Allows us to create derived properties also.
if (!strncmp(property, "fav_num_monday", 14)) {
return state->fav_num_monday;
} else if (!strncmp(property, "fav_num_not_monday", 18)) {
return state->fav_num_not_monday;
} else if (!strncmp(property, "is_monday", 9)) {
return state->is_monday;
} else if (!strncmp(property, "fav_num", 7)) {
return state->is_monday * state->fav_num_monday +
(1 - state->is_monday) * state->fav_num_not_monday;
}
}
int main() {
// Set the state.
struct State state;
state.fav_num_monday = 12;
state.fav_num_not_monday = 5;
state.is_monday = 1;
// Print favourite number in different ways.
printf("\n1) Current favourite number is %d.",
state.is_monday * state.fav_num_monday +
(1 - state.is_monday) * state.fav_num_not_monday);
printf("\n2) Current favourite number is %d.",
get_state(&state, "fav_num"));
printf("\n3) Current favourite number is %d.",
state_fav_num);
printf("\n");
return 0;
}
You can get the best of both worlds (function and macro) for readability and performance, with a static inline function.
You usually wouldn't use that, but if you know the compiler is going to optimize its code away, then it's OK to use it. The usual rule I use is 3 or less lines of code, and the function should require extra performance.
That said, your get_state doesn't meet the (my) requirements for a static inline function, but if you only want a function to get only the fav_num, it would make sense:
struct State {
int fav_num_monday;
int fav_num_not_monday;
bool is_monday;
};
static inline int get_fav_num(const struct State *state)
{
if (state->is_monday)
return state->fav_num_monday;
else
return state->fav_num_not_monday;
}
int main(void)
{
struct State state;
int fav_num;
state = (struct State){
.fav_num_monday = 12;
.fav_num_not_monday = 5;
.is_monday = 1;
};
// Print favourite number in different ways.
printf("\n");
if (state.is_monday)
fav_num = state->fav_num_monday;
else
fav_num = state->fav_num_not_monday;
printf("1) Current favourite number is %d.\n", fav_num);
fav_num = get_fav_num(&state);
printf("4) Current favourite number is %d.\n", fav_num);
return 0;
}
Disclaimer: This code needs C99 or later.
Although here the code is all together, the struct State {...}; and the static inline function would usually go in a header .h file.
Also, I would improve your get_state function in this way:
enum Properties {
FAV_NUM_MONDAY,
FAV_NUM_NOT_MONDAY,
IS_MONDAY,
FAV_NUM
};
int get_state(const struct State *state, int property)
{
switch (property) {
case FAV_NUM_MONDAY:
return state->fav_num_monday;
case FAV_NUM_NOT_MONDAY:
return state->fav_num_not_monday;
case IS_MONDAY:
return state->is_monday;
case FAV_NUM:
return get_fav_num(state);
default:
return -1; /* Error */
}
}
This function would be a usual extern function and would go in a .c file, although the enum Properties should go in a header file so that it can be used by the user of the function.
Edit: Add high performance version using array
state.h
#include <stdint.h>
enum State_Properties {
FAV_NUM_MONDAY,
FAV_NUM_NOT_MONDAY,
IS_MONDAY,
STATE_PROPERTIES
};
static inline
uint_fast8_t get_fav_num(const uint_fast8_t *restrict (state[STATE_PROPERTIES]))
{
if ((*state)[IS_MONDAY])
return (*state)[FAV_NUM_MONDAY];
else
return (*state)[FAV_NUM_NOT_MONDAY];
}
main.c
#include <inttypes.h>
#include "state.h"
int main(void)
{
uint_fast8_t state[STATE_PROPERTIES];
uint_fast8_t fav_num;
uint_fast8_t fav_num_monday;
state = (uint_fast8_t [STATE_PROPERTIES]){
[FAV_NUM_MONDAY] = 12;
[FAV_NUM_NOT_MONDAY] = 5;
[IS_MONDAY] = true;
};
// Print favourite number in different ways.
fav_num = get_fav_num(&state);
printf("5) Current favourite number is %"PRIuFAST8".\n", fav_num);
// Example of how to retrieve any property:
fav_num_monday = state[FAV_NUM_MONDAY];
}
Of course you can change the type to anyone you want. I used uint_fast8_t, because your data can fit in there, and it is the fastest type on any system.

Which lookup method is most efficient for simple integer to string lookup

I need to lookup string identifiers in some C code and was thinking about how to code the lookup. The identifiers and strings are fixed at compile time and are not likely to change. I thought that an index into an array of strings would be the most efficient - that is lookup1.
Sometimes in the code the identifier does not start from 0 or there are gaps in the numbering so chose lookup2 for those cases. lookup2 uses a switch statement.
Another option is lookup3 which uses a struct with an integer to string mapping.
Some pros and cons I thought about.
lookup2 is more flexible if identifiers do not start from zero or if there are gaps
If identifiers start from zero and there are no gaps then lookup1 is better? If not then go for lookup2 method?
How about lookup3?
This is legacy code and the defines are already there. For new code, enums would be better for this?
Generally there would be say 5-20 defines in a category. There can be over 100.
Here is the code.
#include <stdio.h>
#define RINGING 0x0
#define DIALING 0x1
#define IDLE 0x2
#define ENGAGED 0x3
#define CONNECTED 0x4
static const char* const lookup1(int id) {
static const char* const identifiers[] = {
"RINGING",
"DIALING",
"IDLE",
"ENGAGED",
"CONNECTED" };
int size = sizeof(identifiers) / sizeof(identifiers[0]);
if (id >= 0 && id < size) {
return identifiers[id];
}
return "Unknown identifier";
}
static const char* const lookup2(int id) {
switch (id) {
case RINGING: return "RINGING";
case DIALING: return "DIALING";
case IDLE: return "IDLE";
case ENGAGED: return "ENGAGED";
case CONNECTED: return "CONNECTED";
default: return "unknown";
}
}
static const char* const lookup3(int id) {
struct id2name {
int id;
const char* const name;
};
static struct id2name pairings[] = {
{ RINGING, "RINGING" },
{ DIALING, "DIALING" },
{ IDLE, "IDLE" },
{ ENGAGED, "ENGAGED" },
{ CONNECTED, "CONNECTED" } };
int size = sizeof(pairings) / sizeof(pairings[0]);
if (id >= 0 && id < size) {
return pairings[id].name;
}
return "Unknown identifier";
}
int main() {
const int identifiers[] = { RINGING, DIALING, IDLE, ENGAGED, CONNECTED };
const int size = sizeof(identifiers) / sizeof(identifiers[0]);
for (int i = 0; i < size; ++i) {
printf("using lookup1 id %d is: %s\n", i, lookup1(i));
printf("using lookup2 id %d is: %s\n", i, lookup2(i));
printf("using lookup3 id %d is: %s\n", i, lookup3(i));
}
}
It's hard to beat a table lookup such as your lookup1() for clarity, concision, and speed. That's not to say, however, that other approaches might not compete at least on speed. For relative performance questions, you really need to benchmark.
If the maximum index number is large or if any of the index numbers are less than zero, or if you cannot rely on at least C99, then a direct array-based table lookup is problematic, but otherwise, gaps between the indexes are not a particular problem, including between the start of the array and the lowest index used. Consider this:
#define INITIALIZER(x) [x] = #x,
const char *lookup4(int x) {
static const char * const table[] = {
INITIALIZER(RINGING)
INITIALIZER(DIALING)
INITIALIZER(IDLE)
INITIALIZER(ENGAGED)
INITIALIZER(CONNECTED)
// initializers have the form:
// [MACRO] = "MACRO",
};
const char *result = ((x < 0 | x >= (sizeof(table) / sizeof(table[0])))
? NULL
: table[x];
return result ? result : "unknown";
}
That uses designated initializers (produced by the INITIALIZER() macro) to initialize those elements of the lookup table that correspond to valid strings; the others will be NULL. This ends up being pretty closely analogous to your lookup1().
There's nothing particularly wrong with your lookup2(). It's clean and clear, and I imagine most compilers will produce very efficient code for it.
As lookup3() is presented, however, I don't see any reason to prefer it over any of the others. You don't use the message numbers, so why store them in your struct? Without them, however, you don't need a struct, so you basically have a more complex implementation of lookup1(). If you did use the numbers -- e.g. by performing a search through the array for the requested message number -- then that would be more expensive on average than the other approaches.
If identifiers start from zero and there are no gaps then lookup1 is better?
Yes.
If not then go for lookup2 method?
Yes.
How about lookup3?
lookup3 is buggy. You need to iterate all the pairings and check for an ID, i.e.:
static struct id2name pairings[] = {
{ RINGING, "RINGING" },
{ DIALING, "DIALING" },
{ IDLE, "IDLE" },
{ ENGAGED, "ENGAGED" },
{ CONNECTED, "CONNECTED" } };
int size = sizeof(pairings) / sizeof(pairings[0]);
for (i = 0; i < size; i++) {
if (pairings[i].id == id) {
return pairings[i].name;
}
}
If the IDs in pairings[] are sorted, you can break the for loop sooner, i.e.
for (i = 0; i < size && pairings[i].id < id; i++) {
For new code, enums would be better for this?
Not in terms of performance, but they will look nicer.

Resources