所以我需要从 C 中的一些变量中删除常量(我知道我在做什么)。所以我写了一个小宏 ( UNCONST
),它可以让我为 const 值分配一个新值。这对于像int
. 但这不适用于指针。UNCONST
所以我不能在没有得到编译器警告的情况下使用我的宏让指针指向不同的位置。
这里有一个小测试程序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);
}
编译和执行
$ 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
有没有办法优化我的宏,所以这个警告不会出现?