2 ms·
Now you have to make `f` nullable and you run the risk of not initialising it and getting a null pointer. You can't do it in C, but in functional style languag
by IshKebab 2y ago
Now you have to make `f` nullable and you run the risk of not initialising it and getting a null pointer.
You can't do it in C, but in functional style languages you can do this:
let f = {
let bar = ...;
let baz = ...;
let barbaz = ...;
barbaz
};
Which is a lot nicer. But if you ask me it's just a function by another name except it still doesn't limit scope quite as precisely as a function.
- nikki93 2y agoGCC and clang (and maybe others) have 'statement expressions': https://godbolt.org/z/sqYnbh4Ej https://godbolt.org/z/sqYnbh4Ej
- int_19h 2y agoIn C++ you can do: auto f = [&] { ... return barbaz; }(); with the side benefit that you can also make the use of state explicit inside of [] instead of using wildcard capture. Given that it's neither reused nor parametrized, I'm not sure why you see this kind of pattern as a "function by another name", though. Semantically it's more of a namespace if anything.
- IshKebab 2y agoThat literally is a function. I guess the important difference is you can easily confirm by inspection that it is only called once? If that's an important property maybe it would be worth supporting an annotation on normal functions to enforce that. I guess you could easily write a linter for that.
- int_19h 2y agoSyntactically it is, but semantically it's really more of an isolated block IMO because not only it's called only once, but that call happens immediately (so no back-and-forth control flow unlike regular functions), and the lambda is not passed anywhere as a value either.