Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid or warn on implicit conversion from const char* to bool in GCC

Consider the following code:

void foo(bool parameter) {
    std::cout << parameter << "\n";
}

int main() {
    foo("const char *argument");
}

I want the compiler to raise a warning when passing const char* instead of bool as a parameter to function foo.

But GCC implicitly converts it. I tried -Wall, -Wextra, and -Wpedantic, but none of these issue a warning. Is there a flag that could catch such an implicit conversion (invalid parameter type)?

Ignore the fact that the function has an argument of type bool, which some may see as bad code style. I can't refactor that part.

The standard just mentions such an implicit conversion will occur:

A prvalue of integral, floating-point, unscoped enumeration, pointer, and pointer-to-member types can be converted to a prvalue of type bool.

I know such behavior is very convenient in if (ptr) statements, but for me, in the case of passing parameters, it is clearly wrong and a source of bugs.

like image 286
Szymon Zimnowoda Avatar asked Feb 04 '19 12:02

Szymon Zimnowoda


2 Answers

You could declare an overload of foo for pointers as deleted:

template <class T>
void foo(T*) = delete;

Or better yet, as @Ted comments, simply declare a vanilla overload to not compile any implicit conversions:

template <class T>
void foo(T) = delete;
like image 85
Paul Evans Avatar answered Nov 15 '22 10:11

Paul Evans


I want the compiler to raise a warning when passing const char* instead of bool as a parameter to function foo. ... I tried -Wall, -Wextra, and -Wpedantic

You need to add -Wconversion to your compiler flags. Note that seems to work with clang (recent or older version), but not with gcc.

If this triggers too many warnings that you don't want to handle, you can selectively enable -Wstring-conversion (clang only).

like image 26
lubgr Avatar answered Nov 15 '22 09:11

lubgr