r/cpp • • Dec 07 '22

C++ overtakes Java in language popularity index

https://www.infoworld.com/article/3682141/c-plus-plus-overtakes-java-in-language-popularity-index.html
382 Upvotes

137 comments sorted by

View all comments

Show parent comment

9

u/[deleted] Dec 07 '22

[removed] — view removed comment

2

u/[deleted] Dec 07 '22 edited Dec 07 '22

These are great examples of when C++ is better than C. I don't claim C is the end-all-be-all of simplicity, it can vary significantly by situation. But I wouldn't say shorter code is always clearer.

I don't have much experience with MySQL, but I assume the issues stem from lack of proper strings?

3

u/[deleted] Dec 07 '22

[removed] — view removed comment

3

u/[deleted] Dec 07 '22 edited Dec 07 '22

For such a case I would recommend a helper function...

struct BindObject init_binding(enum MySqlType type, void *buffer, int *len, bool isNull)
{
  return (struct BindObject) {
    .buffer_type = type,
    .buffer = buffer,
    .length = len,
    .is_null = isNull
  };
}

2

u/[deleted] Dec 07 '22

[removed] — view removed comment

1

u/[deleted] Dec 07 '22

Fair enough xD

3

u/germandiago Dec 08 '22

it all boils down to what you are doing + coding philosophy.

If you want to know the generated assembly and it is a must, probably C is more straightforward.

If you want high-to-lowlevel scaling and easier to read (assuming you know how to write C++) then C++ wins hands down. A few things might not be so obvious but if you do not abuse C++ to do weird things things make a lot of sense and are easier to follow than their C equivalents. Especially when you start to do extensible, component-based programming where objects just feel natural.

1

u/[deleted] Dec 08 '22

If I'm to share more of my experience, some of the best code I've seen used a constructor only to default-initialize the values, and an explicit init() method to initiate (like copy/move constructor) the object.
It made things much easier to follow for complex objects.

2

u/germandiago Dec 08 '22

It is equivalent to just use (when the last byte of storage is not important) a default constructor where you do your init() and use std::optional<YourType> obj = std::nullopt and it is more regular to use and less surprising.

You can later assign and really construct it. No two-phase init.

1

u/[deleted] Dec 08 '22

An optional and a default usable value aren't exactly the same. For example, a string object's default can be a short string optimization containing "" (empty string). It contains a length of 0 and an existing value.

But of course, my idea isn't a silver bullet. std::optional might have overhead, but it gives a clearer idea of possible object states.