← Back to context

Comment by AnimalMuppet

3 days ago

C++ can do some of that. Let's say I want an if statement that takes an integer and three blocks of code. It executes the first block if the integer is less than zero, the second if it is zero, and the third if it is positive.

OK, if you squint enough that by "block of code" you mean closure, or function object, then I can write that in C++. I can make the if statement a free-standing function (that is, not a member of a class), and add it to any library I wish.

Now, you can say that it's going to be tedious to use that, because you have to set up three closures every time you want to call this "super if". And you'd be right, but that's a different argument.

One problem is that closures don't actually behave like blocks. Consider that you might want to use this three-legged-if inside a loop. If it's a real statement, then those branches can have `break;` and `continue;` statements which affect the surrounding loop. If those branches are just closures being passed to a function, then they can't.

> OK, if you squint enough that by "block of code" you mean closure, or function object,

But we aren't squinting here; those closures can't perform a return where your `new-if` function is being used, they can't perform a `return` like a proper `if` can, you can't goto, or break or continue.

It's just a function taking functions, with all the restrictions that that entails.

How can you declare new syntax in C++? Wouldn't it just be a function call?

  • Yes, a function call. Not new syntax. But as a function, it would be trivial to add to a library.

    My point was that you can often get the effect you want with no new syntax. (Cue 10,000 replies that state "but you can't get this effect without new syntax!" Perhaps not. Many of those tend to be rather contrived, though. I'm more sympathetic to the argument that new syntax would make something less clumsy. If it's something you need to do a lot, that matters.)

    • Yes - I see what you mean. There are degrees of ease of use at between - at the extremes - what writing assembly provides, which technically can do it too, and what something like, say, Haskell provides. C++ is of course closer to Haskell than Assembly, but there's still quite a headache in using your solution that is down to absent C++ language features.