0
  int arr[10];
  void* p1 = arr;
  void* p2 = arr + 10;
  size_t sz = p2 - p1;

The same code, on the C++ side, it doesn't compile. But on the C side, it compiles. And the result sz is 40. enter image description here

I know why it doesn't compile on C++ side, because void does't have size so it can't do subtraction. But what's for the C side?

I guess C treat void* as int*, right?

Zhang
  • 3,030
  • 2
  • 14
  • 31
  • 8
    [You shouldn't be doing it in C either: it's UB](https://stackoverflow.com/questions/36615981/c-what-type-is-the-difference-of-two-void-pointers). – Dai Mar 16 '22 at 04:14
  • 1
    Why should the behaviour in C and the behaviour in C++ have anything to do with each other? "I know why it doesn't compile on C++ side... But what's for the C side?" Then this *isn't a C++ question*. The fact that it's valid C++ code isn't relevant to understanding why it isn't valid code in C; they are different languages despite the history. – Karl Knechtel Mar 16 '22 at 04:15
  • @KarlKnechtel it's not valid C++ code either – M.M Mar 16 '22 at 04:18
  • 4
    The code is not valid in either language; the "difference" is that you are using a C compiler which allows some invalid code in its default mode. You can and should use compiler switches to enforce conforming mode – M.M Mar 16 '22 at 04:19
  • 5
    [It's a gcc extension](https://gcc.gnu.org/onlinedocs/gcc-11.2.0/gcc/Pointer-Arith.html) – Artyer Mar 16 '22 at 04:22
  • 1
    If it were treated as `int*` the result would be 10, not 40. – molbdnilo Mar 16 '22 at 08:31

1 Answers1

2

GCC defines an extension to the C language in which addition and subtraction with void * acts like arithmetic on char *.

This makes the compiler non-conforming to the C standard in its default mode because the standard requires the compiler to issue a diagnostic for addition and subtraction on a pointer to an incomplete type. If -pedantic is used, the compiler will issue a diagnostic but still compiles the program (in the absence of additional switches that prevent that, such as -Werror), and then the compiler conforms to the C standard in this regard.

When compiling for C++, which has stricter typing rules, GCC does not provide this extension.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312