4

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()
Chris Holt
  • 655
  • 1
  • 6
  • 19
  • 1
    These are analogous to default c'tors (see https://stackoverflow.com/q/5113365/1424875 and links from there) – nanofarad Mar 23 '23 at 22:56
  • 1
    https://en.cppreference.com/w/cpp/language/value_initialization – NathanOliver Mar 23 '23 at 22:58
  • So that condition is basically an `if (false)`. No wonder it never worked. – Dan Mašek Mar 23 '23 at 23:01
  • This question does demonstrate why caution is needed with using type aliases for basic types like `char` - such things have their place, but also their pitfalls (which is true of features of any programming language). I'd say the bigger problem in the code-base the OP is working with is the fact that it appears some developer *assumed without checking* that `ProfileType` was the name of a (member) function rather than a type alias. I'd suggest a high chance of other hidden flaws as well - such things are rarely one-offs. – Peter Mar 24 '23 at 04:00

1 Answers1

5

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
Daniel
  • 30,896
  • 18
  • 85
  • 139
  • Thank you!. Once again I'm reminded about how horrible c/c++ is as a language. And I used to think I was actually competent at at! – Chris Holt Mar 24 '23 at 00:04
  • That's because C/C++ isn't a language. C and C++ are distinct languages; for example, C++ has inheritance and C doesn't. – Thomas Matthews Mar 24 '23 at 01:08
  • 1
    There is nothing particularly wrong with the syntax `char()` to get a zero-initialised `char` - it is well specified and consistent part of C++, and (arguably) preferable over the `(char)0` that is part of C to get the same effect. This question doesn't demonstrate a typical usage of the syntax though. – Peter Mar 24 '23 at 04:01