Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does gcc -Wdiscarded-qualifiers complain about this code?

I were writing a qsort compare function callback for this scenario:

int matrix[3][4] = 
{
  {1,2,3,4},
  {5,6,7,8},
  {9,1,2,3},
};

qsort(matrix, 3, sizeof(int[4]), compare);

Since the item type is int[4] then qsort should pass me int(*)[4] pointers converted to const void*.

So I wrote the function like this:

int compare (const void* obj1, const void* obj2)
{
  const int (*ptr1)[4] = obj1;
  const int (*ptr2)[4] = obj2;
  /* ... */
  return 0;
}

gcc 12.2 x86 -Wall -Wextra -std=c17 -pedantic-errors complains about the const int (*ptr1)[4] = obj1; lines:

error: initialization discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]

Why am I getting this warning? There are no const qualifiers being discarded as far as I can tell. The type being a pointer to an array of 4 const int. Apparently this warning goes way back to older gcc versions too.

Whereas clang and icx with the same options compiles the same code cleanly and the end result works fine on all 3 compilers.

like image 299
Lundin Avatar asked Oct 21 '25 07:10

Lundin


1 Answers

Because by passing -pedantic-errors you are requesting pedantic diagnostics, and, pedantically, const int[4] is not a const-qualified type (it's an array of const elements, and the array itself cannot be qualified). See GCC bug 62198.

gcc-5.1 and newer do not issue this warning in non-pedantic mode.

like image 67
amonakov Avatar answered Oct 23 '25 22:10

amonakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!