Friday, November 4, 2022

[FIXED] Why don't we add parenthesis when writing comparator in c++?

Issue

Here is a code explaining what I mean.


static bool comparator(int a, int b) {
    if(a > b) return false;
    return true;
}

sort(arr.begin(), arr.end(), comparator); // why don't we write comparator()


Solution

If you will write

sort(arr.begin(), arr.end(), comparator());

then it means that the argument expression of the function std::sort comparator() must be evaluated. But neither arguments are supplied to the function call comparator(). So the compiler will issue an error message.

On the other hand, if you will write

sort(arr.begin(), arr.end(), comparator);

then the function designator comparator is implicitly converted to a pointer to the function and the function std::sort within itself will call the function using the pointer and supplying two arguments to it.



Answered By - Vlad from Moscow
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.