Home > Software engineering >  void pointer subtraction can't compile in C , but can compile in C, what's the reason for
void pointer subtraction can't compile in C , but can compile in C, what's the reason for

Time:03-17

  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?

CodePudding user response:

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.

  •  Tags:  
  • c c
  • Related