Search code examples
c++clion

Code that compiles in C++ but has no obvious meaning. Function call operator applied to a simple type such as char


This compiles in C++

    if (char()=='a') {

    }

I discovered this after opening a very old project in CLion (Yeah Jetbrains!). The code in question was trying to do this:

    if (ProfileType()==GI_PROFILE_TYPE && forEdit && 
        !user.AccessGranted(AK_GI_MOD))
        return false;

with the assumption that ProfileType() was a member method to return the type of a profile. But it wasn't. It was this:

typedef char            ProfileType;

It should have been

GetType()

This code has silently compiled for years (decades?) and never actually worked properly. I only found this because I noticed that CLion gave the warning that the condition was always false. At first I doubted the warning, and then I doubted the navigate-to, and then I realized the warning was actually correct! I've run several static analysis tools on this code over the years and nothing ever caught this mistake till now. I build with gcc -Wall and it didn't complain about this either...

My question is: what does this actually mean:

char()

Solution

  • This is a syntax for the default constructor, e.g.

    auto x = MyClass();
    

    Will call the default constructor of MyClass. For primitive types like char, it zero initializes them, e.g.

    char() == 0