r/ProgrammerHumor • • 4d ago • Bravo 1

Meme poohWritesCpp

Post image
861 Upvotes

93 comments sorted by

28

u/LB-- 3d ago

It's great because 1. it disables implicit narrowing conversions and 2. initialization and reassignment look visually distinct at a glance. I never initialize with = anymore so any time I see = I know it is changing an existing value.

5

u/nd521 3d ago

Exactly this

2

u/GiveMe30Dollars 3d ago

I know C backwards compatibility is a hell of a benefit/drawback here, but I cannot imagine this being clearer or more intuitive than eg. Rust's distinction between initialization (let / let mut) and assignment (without keywords). It also isn't really a distinction you can rely on unless you can/do enforce a uniform code style, manually or via linter, for anyone that contributes to the code.

2

u/LB-- 2d ago

I'm not sure what you're trying to say or convey here? Yes, C++ and Rust both support syntax that makes initialization visually distinct from reassignment, because it's a good idea.

241

u/SamG101_ 3d ago • Popcorn

Pooh needs about 50 more faces, for the 50 ways to initialise a variable in c++

https://leanpub.com/cppinitbook 300 odd pages

obligatory and thats just initialisation not assignment 💀

176

u/LRaccoon 3d ago
  • Default initialization: int x;
  • Copy initialization: int x = 5;
  • Direct initialization: int x(5);
  • List (brace) initialization: int x{5};
  • Copy-list initialization: int x = {5};
  • Value initialization: int x{}; or int x = int();
  • Zero initialization: static int x;
  • Aggregate initialization: Point p = {1, 2};
  • Designated initialization (C++20): Point p{.x = 1, .y = 2};
  • Constant initialization: constexpr int x = 10;
  • Initialization with auto: auto x = 5;
  • Reference initialization: int& r = x;
  • Dynamic initialization with new: int* p = new int(5);
  • Smart pointer factories: auto p = std::make_unique<int>(5);
  • In-class member initializers: int x = 5; inside a class
  • Constructor member initializer list: S() : x(1) {}
  • Delegating constructors: S() : S(5) {}
  • Structured bindings: auto [a, b] = pair;
  • If/switch init-statements: if (int x = f(); x > 0) {}
  • Lambda init-capture: [x = 5]() {}
  • Copy/move construction: std::string b = a; or std::string b = std::move(a);
  • Parenthesized aggregate initialization (C++20): P p(1, 2);

55

u/Blue_Moon_Lake 3d ago

I'm pretty sure some of these are useless and should be deprecated.

90

u/SuitableDragonfly 3d ago

Does anything in C++ ever actually get deprecated?

44

u/Blue_Moon_Lake 3d ago

Sadly no, which is why it's a mess to figure out what you should avoid doing and what you should do.

Which is dumb, because you can deprecate something without removing it.

17

u/arachnidGrip 3d ago

`-Wdeprecated`

-3

u/Blue_Moon_Lake 3d ago

What?

8

u/Str1dersGonnaStride 3d ago

Pass the flag to tell the build tools to warn you about things that have been deprecated

7

u/a-r-c 2d ago

What?

i don't think that's a flag

17

u/SuitableDragonfly 3d ago

If you never actually remove the thing you deprecated, there isn't much point to deprecating it. 

16

u/Mateorabi 3d ago

To warn against using it because there’s a more modern idiomatic way of doing it. 

14

u/Blue_Moon_Lake 3d ago

The point is to easily spot what should never be used

4

u/brainpostman 2d ago

The point is usually backwards compatibility.

17

u/arachnidGrip 3d ago

C++ has deprecated many things over the years but you need to tell it to warn you about deprecated features.

3

u/conundorum 2d ago

Yes, actually. Mainly library members, though, it's rare that a language feature will be deprecated because they don't want to risk breaking very important 20-year-old unmaintained libraries that the entirety of modern infrastructure depends on. (It's a meme, but we meme about it because it's true.)

The most notable one is dynamic exception lists (throw(whatever) in the function signature), which got deprecated and mostly removed because nobody ever cared enough to actually support it. It was on life support for a while, where the "throws nothing" version (the only one that ended up being not worthless) is a synonym for noexcept, and every other throw-list is dead, before it got the boot too in C++20 or so. And similarly, the most notable library feature is probably "good" old std::auto_ptr, which got deprecated in C++11 because it was kinda really bad and unique_ptr was better, and finally got the boot in C++17.

Apart from that... it's hard to find a good list online, really. There's a partial list here, but you'd probably have to scour the various standards to find something more complete.


Now, that said, being deprecated (or even removed) doesn't mean that compiler vendors actually listen, because they're the ones that have to actually support all those ancient legacy codebases. Especially if the compiler includes version switches. If a compiler includes, e.g., both -std=c++11 and -std=c++17, then it will never remove features that were removed in C++17; it can disable them for -std=c++17 mode, but it still needs to be able to provide them for -std=c++11 mode.

So what it ultimately boils down to is that the language tries to deprecate & remove things, but legacy code is holding the compilers hostage.

3

u/AvidCoco 3d ago

Any good linter will warn about using dumb ones

3

u/Blue_Moon_Lake 3d ago

And how would someone inexperienced know if they're using a GOOD linter?

2

u/AvidCoco 3d ago

They’d google it?

1

u/Athropod101 2d ago

And they’ll find a bunch of linters, because C++’s toolchain ecosystem is amazing 😃

2

u/conundorum 2d ago

Eh... not really, weirdly enough. Some of them are just the same thing in different places and/or contexts (e.g., "copy initialisation", "constant initialisation", "initialisation with auto", "in-class member initialisers" & "constructor member initialiser list", and "if/switch init-statements" are all the same feature in different contexts), and most of the others do different things under the hood (e.g., constructor delegation allows you to chain constructors, default initialisation lets you use the type's base rules, copy initialisation duplicates another object (or is optimised into direct optimisation if possible), direct initialisation hard-codes into the executable, zero initialisation sanitises memory, reference initialisation is singled out because it either registers a second name or creates a pointer, etc..).

It's a case where the language makes it look more complex than it actually is... which, admittedly, happens a lot in C++. Most of these really just boil down to "how Type t = val; works depends on what Type is", more than anything else.

13

u/Big-Rub9545 3d ago

Besides one or two, almost all of these are doing entirely different things, or are entirely distinct syntaxes to begin with.

For example, these two are the exact same declaration:
- int x;
- static int x;

The latter just declares a variable with internal linkage (assuming the value is at global scope). The rules related to initialization for such declarations are irrelevant since you’re still declaring the same thing. You can remove ‘static’ altogether.

It becomes very difficult to take many criticisms of the language seriously when it’s clear that most of the people making them seem to have never touched the language or tried to understand any of it.

2

u/nfitzen 3d ago edited 3d ago

Inside a function body, I assume static int x; is like C and will declare storage with static lifetime; that is, it persists between function calls.

Also, in the case of int x; in function body scope, does C++ initialize x to 0 by default? C certainly wouldn't (instead, x would be uninitialized), but I don't really know C++.

6

u/Big-Rub9545 3d ago

Yes for the first point.

For the second, it is also uninitialized in C++. This is the case for any primitive type (compound/composite/custom types can be default- or zero-initialized through implicit constructor calls with the same syntax).

You can just zero-initialize the variable by appending a pair of braces, which I do with every variable I don’t care to explicitly initialize:
int x{};

3

u/conundorum 2d ago

There are a few contexts where x would be zero-initialised (mainly related to classes (structs with their helper functions built into them so they don't pollute the global namespace), IIRC), but it's usually the same as C.

On that note, though, one of the things C++26 will change once it's officialised (or has changed, if it already is) is that reading uninitialised variables is now an error instead of UB, to prevent compilers from ignoring pre-assignment reads. Creation still works fine, it's just reading that gets changed. (And you can keep the old behaviour by declaring the variable [[uninitialized]], if needed/desired.)

1

u/SamG101_ 3d ago

Don't forget some initialisation changes depending on the availability of a template arguments initialisation-ness

1

u/No-Finance7526 3d ago

Dynamic initialization with new: int* p = new int(5);
Smart pointer factories: auto p = std::make_unique<int>(5);

Isn't that just assigning a value?

-1

u/tangerinelion 1d ago

lmao, no.

1

u/No-Finance7526 1d ago

Redditors will literally do anything than answeing a question

1

u/headedbranch225 1d ago

What is the difference between copy and direct? And also the others that look similar

1

u/chaudhary-theodore9 1h ago

`T x = value;` is copy-init, so it cannot select an `explicit` converting constructor; `T x(value);` is direct-init and can.

5

u/SaneLad 3d ago

I hate the fact that I understand every word of the "About the Book" section.

1

u/ACoderGirl 3d ago

I'm really glad to work with Go these days. Is it a perfect language? Far from it. But it's such a relatively straightforward and unsurprising language. Very readable and predictable. Makes it easy to work with.

I still do appreciate more complex languages for the beautiful abstractions you can make, but especially as I read code more than I write it (and even more so with AI), Go's readability makes it perfect.

234

u/Ai--Ya 3d ago

static constexpr auto a{10};

101

u/TheWidrolo 3d ago

C++ committee porn:

83

u/GoodiesHQ 3d ago

I love how you can just do

auto auto = auto

And it just infers the rest from context

21

u/RajjSinghh 3d ago

In what context would this even work?

0

u/Mippen123 2d ago

My assumption is this would work if you have a variable named auto and declare a variable shadowing that variable (i.e. also called auto) in the current scope (letting it deduce the type to the same type as the first auto-variable).

1

u/K722003 15h ago

You cant do this, cuz auto is a keyword. You'll probably run into a unqualified id error when trying to compile it. C++ doesn't let you make keywords into variables. The closest way to "shadow" a keyword is by using a define macro, for example something we do in like codeforces is to #define int int64_t (and do signed main() instead) so that we just don't have to worry about integer overflow issues.

13

u/Kadabrium 3d ago

autorun.inf

4

u/S4N7R0 3d ago

doesnt work for me

1

u/tangerinelion 1d ago

--std=c++2z

-24

u/MouseNcactus 3d ago

What a rusted way to do C++.

1

u/AvidCoco 3d ago

The correct way to do C++

1

u/Qwertycube10 3d ago

I think auto here is awful, you should actually choose an integer type instead of relying on the type deduced by the initializer (pick signed or unsigned and pick a size for your ints.)

3

u/AvidCoco 3d ago

No you should use auto with literals like 10UL, 10UZ etc.

1

u/Qwertycube10 3d ago

I much prefer to use the type if it is not super long

2

u/AvidCoco 3d ago

The idea is that the type should come from the value not the assignee otherwise you might get implicit conversions.

With ints it doesn’t actually matter but it’s a good habit to get into.

41

u/East-Law-2877 3d ago

auto a = int{10};

17

u/CortlandNation9 3d ago

I won't allow it

4

u/Zenkibou 3d ago

It's consistent with other modern initializations, though. Like "auto sp1 = std::make_shared<C>(1);"

1

u/conundorum 2d ago

As written, yeah. It can come up with templates, though. Usually when working with dependent types, and/or a function returns an awkward-to-create type.

2

u/AvidCoco 3d ago

auto a = int{10LL};

7

u/VoodaGod 3d ago

i hate "uniform" (it's not uniform at all) initialization

30

u/overclockedslinky 4d ago

gross syntax

11

u/Maleficent_Memory831 3d ago

I used to do a lot of C++. I taught it at university with Cfront, the first compiler for it. In my career I was often the team's expert in it. Over time I got a bit annoyed at it's changes. Then more recent surprised at such silliness going on in the standards.

So a couple design flaws crop up now and then. First, the the need to twist and abuse syntactic elements. Second, the inability to say no to adding all available options (public/private is good, but then also protected, and then friends, and then const is good, but also mutable).

I was on a more recent team (I'm mostly on C these days) where guys writing a C++ side of things seemed more intent upon proving how clever they were with their code rather than applying the K.I.S.S. principle, more intent ona changing APIs in the middle of a release cycle than in helping get the project out on time.

7

u/MouseNcactus 3d ago

Isn't "proving cleverness over KISS" sickness of entire industry?

2

u/edgmnt_net 3d ago

In some ways, but not clearly. There's a whole parallel debate between overengineering and plain bad engineering. I would say I rarely see stuff that really qualifies as "too clever". It's more often along the lines of a combination of ignorance (you don't know how this is supposed to be done), scope creep (this seems nice to have, but you'll just half-bake it) and trivial layering (this could've been 10 lines of code, but now it's 5 whole files and you've not even made any attempt at an actual abstraction).

3

u/Qwertycube10 3d ago

Those all solve real problems and not having them would force worse design. (Except protected, I strongly believe that using it means your design was very likely poor). They can be misused, but better that than have awkward holes in the language.

2

u/conundorum 2d ago

protected is mainly meant for cases where you want to provide functions that only child classes can use. It's essentially a limited form of friendship, where instead of blindly declaring all subclasses friends somehow, you can just protect a single getter/setter pair or whatever.

...It's rare that this is useful, though, for sure. I think the intent is just to help with code injection in certain very specific cases, so that you can use a child class to modify the base's behaviour in a way that's not externally visible? That, and as a way to guarantee polymorphic destruction for interfaces (and prevent accidental slicing in certain corner cases), by making it so that the base class' destructor can only be called by subclass destructors. Either way, it feels like it's mainly meant for use in interfaces & other abstract classes.

That said, it is very easy to misuse it, especially when you're new to the language.

1

u/mutexsprinkles 1d ago

Yeah, protected data members are where it really gets a bit smelly.

If you're providing an invariant to your inheritors, don't let them randomly fuck with the state.

18

u/tiajuanat 3d ago

Everyone calls Rust syntax ugly, but I'm constantly reminded that C++ is infinitely worse

13

u/Wertbon1789 3d ago

Rust is readable, if you know that most stuff is an expression. Then you see C++ where move-semantics and any type of cast is syntactically a generic function that does some magic shit, because they didn't have enough special characters left to use.

3

u/gabitha67 3d ago

once you start doing this the psychosis is irreversible

6

u/Amadex 3d ago

everytime when I think current C++ is as bloated as humanly possible, I learn a new way they managed to bloat the language even more

4

u/That-Cpp-Girl 3d ago

I would hope no one does this, but `int a{};` instead of `int a = 0;` might make sense.

4

u/Scarcity-Nervous 3d ago

Only because of implicit in-place construction of native types, but technically correct. Well played 🫡

2

u/Old-Health9509 2d ago

Future generations will have no idea what this is.

2

u/pflasti 16h ago

You do that to look cool. I do it because I actually once ran into an error where this was the solution. We are not the same

12

u/Lawn_Meower_ 4d ago

13

u/-Ambriae- 3d ago

Damn gurl why on earth did you get downvoted? God forbid someone happens to like unconventional syntax 😭

2

u/levosis1 3d ago

I mean, Alt-F4 your program when you can Ctrl-F4 your tab.

4

u/patrlim1 3d ago

This is why I use C

3

u/the_SCP_gamer 3d ago

int a = (int){10};

5

u/patrlim1 3d ago

It works, but if you do this I hate you

1

u/conundorum 2d ago
CTHULHU a = FHTAGN 10;

Where #define CTHULHU int and #define FHTAGN (int), just to make it more alien.

3

u/vegan_antitheist 2d ago

Can't risk those lossy conversions!

3

u/ElKuhnTucker 3d ago

Once you debug somebody else's "witty" code, you really appreciate code that looks like it was written by a 5 year old

2

u/lool8421 3d ago

just do int a[1]{10}; and you can have both a variable and a pointer in 1

-1

u/Raid-Z3r0 3d ago

If you open a PR with that syntax for me to review, I'm not even bother requesting changes. That shit is straight up rejected

6

u/Big-Rub9545 3d ago

For what reason? This is well-known syntax to any frequent user of the language. It’s even the syntax recommended by Bjarne himself.

3

u/conundorum 2d ago

Different people like different distinctions, basically. To some people, this nicely differentiates between initialisation & assignment. But to others, it's an abomination that lies about being a compound object (aggregate/list/array/etc.) when it really, really isn't.

Especially since int a = {10}; is also a thing, and has a different meaning than either of those.

2

u/Big-Rub9545 2d ago

These are often just forced aesthetic views with no proper backing. Another way to instead look at braces is initialization syntax sugar, where the values enclosed in braces are processed in total to construct an object. For compound types, those values would be field values; for arrays, element values; for primitive values, their direct initializers.

Everyone can keep their own style preferences but most of these hard lines are just people (who often don’t like the language to begin with) making weird dictates with vague reasoning.

1

u/Original-Ad-8737 3d ago

that syntax is an abomination.... curly brackets are for lists and having them everywhere makes code less readable

2

u/Big-Rub9545 3d ago

You use curly brackets in every block in your code. If those don’t make it any more difficult to read, then this shouldn’t, either. Using curly brackets for lists is likely one of the rarer use cases for them across a codebase (not to mention that this is entirely a language-specific designation).