简体   繁体   中英

Is it illegal to modify the contents of the qsort's comparison function?

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?

Haris,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM