不使用+符号添加

时间:2016-12-09 12:34:51

标签: c++ c

int add(int a, int b)
{
  return (int)&(((char *)a)[b]);
}

为什么我要将a投放到char *而不是int *

我正在努力完全理解这段代码,但我不能,所以如果你很容易,请提供一个简单的英文解释。

4 个答案:

答案 0 :(得分:6)

The idea is that an array is simply an addition of a pointer with an index. If a is a char [] (or char *) and b is an integer, then a[b] is the value at the address a+b. This code is casting a as a pointer, indexing it with b, and finding the address, which should equal a+b.

But in the real world, don't ever ever ever do this.

答案 1 :(得分:0)

To make it compile you need to turn it into valid c++. Pointers are incompatible with integers, but the distance between two pointers is an integer type:

#include <iterator>

int add(int a, int b)
{
    auto p = (char *)0;
    auto p2 = &(&p[a])[b];

    return static_cast<int>(std::distance(p, p2));
}

Disclaimer: I do not endorse this product or service.

答案 2 :(得分:0)

Why am I supposed to cast a to a char * and not int *?

To clarify for the readers of the question, you aren't supposed to use code like this at all. But let us assume that you're competing in the ioccc (is there a C++ variant of this competition?), in which case this may be exactly what you're supposed to do.

So, to answer the question, it is because pointer arithmetic is scaled by the size of the pointed object. If you used int*, then b would be scaled by sizeof(int). Since you don't want to scale either operand of an addition, you scale with 1 (the multiplicative identity) which happens when the pointed type has the size 1 - which by definition char has.

P.S. The program is ill-formed and may fail to compile on standard compliant compilers.

答案 3 :(得分:0)

Let us take an example with a as 100 and b as 103

  1. (char *)a --> this typecasts a as a pointer. So a will be considered as a pointer.
  2. ((char *)a)[b] --> this is 100[103], i.e. it gives the value at the location (100 + 103)
  3. &(((char *)a)[b] --> this gives the address of the above value, i.e. it gives 203.
  4. (int)&(((char *)a)[b] --> the final typecast to int will convert the address above to an integer value as required by the return value of the function.

This will only work with char* typecast in step 2. If you use an int* typecast there, the sum that you get at step 3 will be 100 + 4*103 i.e. 512