我看到了一个"谜题",你必须在C中编写一个返回值的函数a+c
,但是,你不能使用+
运算符.
unsigned f(unsigned a, unsigned c) { return; }
您只能使用以下字符:harc()&|[]*/
.
这应该在实践中起作用,但我相信它依赖于未定义的行为并会产生警告:
unsigned f(unsigned a, unsigned c) { return &(((char*)a)[c]); }
(实践中需要更少的括号)
其工作原理如下:
(char*)a - cast 'a' to a 'char *' pointer ((char*)a)[c] - treat 'a' as an array, and index the c'th element, which will be at address c + a &(((char*)a)[c]) - take the address of that element, i.e. c + a
最后return
再把它投回去了unsigned
.
琐碎的测试工具,使用gcc 4.8编译并带有两个警告:
#includeunsigned f (unsigned a, unsigned c) { return &(((char *) a)[c]); } int main (int argc, char **argv) { unsigned a = 1; unsigned b = 2; unsigned c = f (a, b); printf ("%d + %d = %d\n", a, b, c); return 0; }
请注意,这是C,而不是C++,它可能无法使用C++编译器进行编译.