【发布时间】:2012-11-15 21:04:57
【问题描述】:
所以我需要从 C 中的一些变量中删除 constness(我知道我在做什么)。所以我写了一个小宏 (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
有没有办法优化我的宏,让这个警告不出现?
【问题讨论】:
-
你知道你可以写 string1 = string2 吗?
-
@Kylo 我没有,但似乎我简化了我的代码太多,我需要编辑问题。
-
使用
int的第一段调用未定义的行为。编译器可能会合法地将i放在只读内存中,然后您可能会遇到崩溃或其他意外结果(例如printf()打印5 而不是6)。您依赖那里的实现的特殊性。因此,当您切换平台或编译器时,预计会出现问题。 -
我的 2c:如果你经常需要“unconst”然后计划那个宏......难道不是其他地方有什么奇怪的地方吗?
-
堆栈溢出经验法则 #4:OP 说“我知道我在做什么”,但他们不知道。
标签: c pointers gcc macros constants