How to declare compare function in header

667 Views Asked by At

I have written compare function for bsearch in c++ class file

int comp(const void* keyBases, const void* offset) {

    myStruct pi = *(myStruct*) keyBases;
    const void* stringInFile = (char*)pi.first + *((int*)offset);
    const void* searchString = pi.second;


    for (int i = 0; ; i++) {
        char firstsChar = *((char*) searchString + i);
        char secondsChar = *((char*) stringInFile + i);
        toLowerCase(firstsChar); toLowerCase(secondsChar);
        if (firstsChar < secondsChar) return -1;
        if (firstsChar > secondsChar) return 1;
        if (firstsChar == 0 && secondsChar == 0) return 0;
    }
    return 0;
}

how to declare it in header file? Is static keyword needed?

1

There are 1 best solutions below

1
On

A function declaration (also known as a function prototype) is just the function header without its body, terminated by a semi-colon. It tells the compiler the return type, the name of the function, and the number and types of arguments.

In your case it would simply be

int comp(const void* keyBases, const void* offset);

Since it's just a declaration it can be anywhere in the same scope as the definition, and you can even have multiple (non-conflicting!) declarations in the same translation unit.

You should only use the static keyword if you define the function (with its full body) in a header file. Or if you define the function as static in a source file (technically in a translation unit), and want a forward declaration of it.