(no title)
dankoncs | 4 years ago
int const& x; // C++
A reference is functionally equivalent to a const pointer. (Reference reassignment is disallowed. Likewise, you cannot reassign a const pointer. A const pointer is meant to keep its pointee [address].) The difference between them is that C++ const references also allow non-lvalue arguments (temporaries).
It is much easier to read from right to left when decoding types. Look for yourself:
- double (* const convert_to_deg)(double const x) // const pointer to function taking a const double and returning double
- int const (* ptr_to_arr)[42]; // pointer to array of 42 const ints
- int const * arr_of_ptrs[42]; // array of 42 pointers to const ints
- int fun_returning_array_of_ints()[42];
Try it out yourself: https://cdecl.org/
Hence, I am an "East conster". (Many people are "West consters" though.)
You can return function pointers:
typedef struct player_t player_t; // let it be opaque ;)
int game_strategy1(player_t const * const p)
{
/* Eliminate player */
return 666;
}int game_strategy2(player_t const * const p)
{
/* Follow player */
return 007;
}int (* const game_strategy(int const strategy_to_use))(player_t const * const p)
{
if (strategy_to_use == 0)
return &game_strategy1;
return &game_strategy2;
}Functional programming = immutable (const) values + pure functions (no side effects).
Consting for me is also a form of documentation/specification.
"East const" for life! :)
harry8|4 years ago
danielozcpp|4 years ago