Search code examples
c++clangclangpowertools

Why does Clang not allow "and" as function name?


I'm developing a program for some time now, using Visual Studio 2017. Lately I installed the Clang Power Tool extension in order to check the quality of my code. Part of my program consists in emulating the opcodes of a cpu. I created a stripped down example below.

The following example works fine :

class C{};

inline void andi(C& s);

int main()
{
    std::cout << "Hello, world!\n";
}

This one does not :

class C{};

inline void and(C& s);

int main()
{
    std::cout << "Hello, world!\n";
}

I'm getting these errors on Clang 3.8.0 (I'm using version 9.0.1 on my program, and errors are similar) :

source_file.cpp:9:18: error: expected ')'
inline void and(C& s);
                 ^
source_file.cpp:9:16: note: to match this '('
inline void and(C& s);
               ^
source_file.cpp:9:13: error: cannot form a reference to 'void'
inline void and(C& s);
            ^
source_file.cpp:9:1: error: 'inline' can only appear on functions
inline void and(C& s);

Looks like that functions named after binary operations (like and, not, or and xor) trigger a wrong behaviour in the compiler. No errors are shown using the Visual Studio compiler, and the program works as expected.

Is there something I can do to prevent this from happening ? Or is this a bug in Clang ? Adding NOLINT to the line doesn't help as it's the compiler which raises the error ...

You can test the case here : https://rextester.com/TXU19618

Thanks !


Solution

  • and is a reserved keyword in C++ which means it cannot be used for a function name. This is standard C++ behavior, not an error.

    https://en.cppreference.com/w/cpp/keyword