So I need to remove constness from some variables in C (I know what I’m doing). So I wrote a little macro (UNCONST) which lets me assign an new value to a const value. This works just fine for normal variables of types like int. But this doesn’t work for pointers. So I can’t let a pointer point to a different position using my macro UNCONST without getting an compiler warning.
Here a little test program unconst.c:
#include <stdio.h>
#define UNCONST(type, var, assign) do { \
type* ptr = (type*)&(var); \
*ptr = (assign); \
} while(0)
struct mystruct {
int value;
char *buffer;
};
int main() {
// this works just fine when we have an int
const struct mystruct structure;
UNCONST(int, structure.value, 6);
printf("structure.value = %i\n", structure.value);
// but it doesn't when we have an char *
char *string = "string";
UNCONST(char *, structure.buffer, string);
printf("structure.buffer = %s\n", structure.buffer);
// this doesn't work either, because whole struct is const, not the pointer.
structure.buffer = string;
printf("structure.buffer = %s\n", structure.buffer);
}
compiling & executing
$ LANG=en gcc -o unconst unconst.c
unconst.c: In function ‘main’:
unconst.c:21:3: warning: assignment discards ‘const’ qualifier from pointer target type [enabled by default]
unconst.c:25:3: error: assignment of member ‘buffer’ in read-only object
Is there a way to optimize my macro so this warning doesn’t show up?
The problem in:
is that
string1is not really const, it can be assigned to, but points to an array of const characters.Actually, doing:
compiles just fine.
Other thing is if you want to copy the array. Then I’d write your macro as this:
And so:
To copy the array of chars you could do:
FOOTNOTE: actually I find this macro rather useless: I find:
as cumbersome as this kind of operation should be.