Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning C4090: 'function' : different 'const' qualifiers

Tags:

c

pointers

I am observing error "warning C4090: 'function' : different 'const' qualifiers " because of below line of code. Going through other similar questions on SO I understand (not 100 percent) it is because of

--> const char* EmployeeList[] and my declaration in qsort of EmployeeList

    #define Elements(array) (sizeof(array)/sizeof((array)[0]))

   const char *EmployeeList[] =
   {
      "Larry Page", "Sergy Brin", "Sundar Pichai", "Merrisa Mayer"
   };

// called from main
SortEmployee(EmployeeList, Elements(EmployeeList));

int Compare(const void *elemA, const void *elemB)
{
 ...
}

void SortEmployee(const char *EmployeeList[], size_t EmployeeCount)
{
    qsort(EmployeeList, EmployeeCount, sizeof(EmployeeList[0]), Compare);
}

However I am unable to resolve it- Any pointers how to do it for array of strings.

like image 832
oneday Avatar asked Oct 21 '25 06:10

oneday


1 Answers

The problem is qsort does not declare its argument as const, while your code does. That means qsort may (in theory) change data, pointed by EmployeeList. So, the compiler reports this error.

Here is the official example: https://msdn.microsoft.com/en-us/library/k77bkb8d.aspx

How ever, here is a simple version to demonstrate my idea:

void foo(char* a) {
   *a = '1'; // I got pointer to char, and changed this char!
}


int main() {
   const char *a = "A"; // I have "CONSTANT POINTER": it points to CONSTANT memory, that CAN NOT be changed (by the way, string constants can't in many environments).
   foo(a); // I pass it to my function, that will change it.
   return 0;
}

Image your compiler stores a in read-only memory (It can, because we told it "this is a pointer to READ ONLY data"). You then modify it (in main function). Something bad may happen. So, the compiler warns you "hey, you pass a pointer to constant data to some function, that does not know that this data is constant and may change it"

like image 161
user996142 Avatar answered Oct 23 '25 20:10

user996142



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!