jeudi 26 février 2015

Is it possible to assign a variable that has a cast prefix? (within a macro)



There are times when its useful to do an assignment in a macro, but this is prevented by casting, eg:



#define SAFE_FREE(v) do { free(v); v = NULL; } while (0)

/* example use */
SAFE_FREE(foo);


however if 'foo' is a 'const int *', a cast is needed.



free((void *)foo); /* OK */


but this fails because of the cast & assignment



SAFE_FREE((void *)foo);


Gives the warning: error: lvalue required as left operand of assignment


One possible solution is to cast in the macro: eg,



#define SAFE_FREE(v) do { free((void *)v); v = NULL; } while (0)


But I'd prefer not to cast within the macro, since this could end up hiding cases where it should warn.




Is there a way to assign a variable in a macro that happens to have a cast prefix?




Aucun commentaire:

Enregistrer un commentaire