56 ms·
Way simpler: from inside out, read any subpart of the type as an expression. (Arrays have precedence over pointers, as usual.) The type that remains is that e
by colanderman 10y ago
Way simpler: from inside out, read any subpart of the type as an expression. (Arrays have precedence over pointers, as usual.) The type that remains is that expression's type. So e.g. given the type:
const char *foo[][50]
the following expressions have the following types:
foo -> const char *[][50]
foo[0] -> const char * [50]
foo[0][0] -> const char *
*foo[0][0] -> const char
Another example:
int (*const bar)[restrict]
bar -> int (*const)[restrict]
*bar -> int [restrict]
(*bar)[0] -> int
One more:
int (*(*f)(int))(void)
f -> int (*(*)(int))(void)
(*f) -> int (* (int))(void)
(*f)(0) -> int (* )(void)
*(*f)(0) -> int (void)
(*(*f)(0))() -> int
(In this case, the last expression is more readily written as f(0)(), since pointers to functions and functions are called using the same syntax.)
- ericye16 10y agoWhat happened to the const in the second example?
- cyphar 10y agoYeah, I think they confused const * with * const
- colanderman 10y agoNope, * const means that the identifier (i.e. thing to the right of the star) is const. That is, in this example, the symbol "bar" is const, not anything that it points to. So once you dereference it, the const no longer matters.
- cyphar 10y agoYou're right, I got confused. const is read as "the thing to the right of me is const". const * means const pointer, * const means pointer to const.
- wruza 10y agoVice versa. Const pointer: int *const p; Pointer to const value: const int *p int const *p >const is read as "the thing to the right of me is const" const is one of storage classes and is read at its order, not just "to the right".
- cyphar 10y agoWow. I literally was staring at my test case when I wrote it and I _still_ got it wrong. I think I need to get some more sleep...
- kr7 10y agoThe pointer itself is const; not what it points to. bar -> const pointer to mutable array of ints *bar -> mutable array of ints And const pointers are dereferenced with * , not (* const), so the rule needs an exception for const pointers (as well as volatile pointers).
- colanderman 10y agoThat const applies only to the bar symbol itself, not to anything it points to. So once bar is dereferenced, the const doesn't matter. The beauty of this method is that it predicts that correctly without having to think about it.
- jcheng 10y agoThis would make a great CLI tool!