Invalid use of 'void'

Игорь Горлов gorlov.igorek@yandex.ru
Mon May 18 10:30:22 GMT 2020


Hi all.

I have an issue when compiling a simple console program on Windows (Msys2).
First, let's consider the program itself:

void.cpp:
#include <cstddef>
#include <cstdlib>
#include <iostream>
int main()
{
// Getting any 2 valid void pointers
void* p1=std::malloc(32);
void* p2=std::malloc(64);
if(p1==nullptr||p2==nullptr)
{
std::cout << "Error: failed to get 2 valid void pointers" << std::endl;
return 1;
}
// Now trying to calculate the difference between these pointers
std::ptrdiff_t difference=p2-p1;
std::cout << "The difference is " << difference << std::endl;
return 0;
}

This program is not compatible with the C++17 standard. However, we can compile it with -std=gnu++17 (C++17 with GNU extensions), because one of that extensions permits calculations on void pointers. Additionally, we append -Wno-pointer-arith to suppress the related warning. So, our command line looks like this:

# g++ void.cpp -std=gnu++17 -Wno-pointer-arith -o void.exe

GCC responds:
void.cpp: In function 'int main()':
void.cpp:16:30: error: invalid use of 'void'
   16 | std::ptrdiff_t difference=p2-p1;
      |                              ^~

What am I doing wrong?


More information about the Gcc-help mailing list