如何使用这些字符创建加法器函数?

kle*_*ium 3 c math function

我看到了一个"谜题",你必须在C中编写一个返回值的函数a+c,但是,你不能使用+运算符.

unsigned f(unsigned a, unsigned c) {
    return <write your coe here>;
}
Run Code Online (Sandbox Code Playgroud)

您只能使用以下字符:harc()&|[]*/.

abl*_*igh 5

这应该在实践中起作用,但我相信它依赖于未定义的行为并会产生警告:

unsigned f(unsigned a, unsigned c) {
    return &(((char*)a)[c]);
}
Run Code Online (Sandbox Code Playgroud)

(实践中需要更少的括号)

其工作原理如下:

   (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
Run Code Online (Sandbox Code Playgroud)

最后return再把它投回去了unsigned.

琐碎的测试工具,使用gcc 4.8编译并带有两个警告:

#include <stdio.h>

unsigned
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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,这是C,而不是C++,它可能无法使用C++编译器进行编译.

  • `错误:从'char*'到'unsigned int'的无效转换是我得到的 (2认同)