Home > Software design >  Is it illegal to modify the contents of the qsort's comparison function?
Is it illegal to modify the contents of the qsort's comparison function?

Time:12-13

I did not find anything about this on the man page, but cppreference.com says:

The signature of the comparison function should be equivalent to the following:

int cmp(const void *a, const void *b);

The function must not modify the objects passed to it and must return consistent results when called for the same objects, regardless of their positions in the array.

Would converting the strings with strtod, atof etc. come under modification and result in undefined behavior or so?

The objective is to sort an array of char * numerically. If it is illegal, do I have to write my own sort routine?

CodePudding user response:

Harris,

A function should only do what it says on the tin. In this case it should only do a comparison.

To aid this and to try to ensure that this is all that is does it uses the keyword const.

So if necessary just take local copies of the data. In most (all?) this is usually not necessary

EDIT

As strtod and atof do not modify the strings they can be used

  • Related