5

In particular I'd like to know what ->val does in the

sizeof(((stoken_t*)(0))->val)

and what stoken_t*(0) pointer do, in particular what the (0) means?

I hope I have formulated my question clearly enough.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Houst
  • 65
  • 5

2 Answers2

6

This is a way of accessing a member of a structure at compile time, without needing to have a variable defined of that structure type.

The cast (stoken_t*) to a value of 0 emulates a pointer of that structure type, allowing you to make use of the -> operator on that, just like you would use it on a pointer variable of that type.

To add, as sizeof is a compile time operator, the expression is not evaluated at run-time, so unlike other cases, here there is no null-pointer dereference happening.

It is analogous to something like

stoken_t * ptr;
sizeof(ptr->val);
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    With the edits my answer is superfluous, good explanation. – Peter Sep 07 '20 at 08:46
  • In general, dereferencing a NULL pointer causes undefined behavior. It's a bit surprising that this is well defined. – August Karlstrom Sep 07 '20 at 08:57
  • 1
    @AugustKarlstrom: This is not the case here since sizeof does not access the memory pointed to by the cast pointer. – Peter Sep 07 '20 at 08:59
  • @Peter Both answers were useful! So if I have understood correctly this code casts a numeric literal that can be any (e.g. (7) ) to a pointer in order to access a variable and consequently use the operator sizeof. And all of this to have it working at compile time and not at run time (I must study a bit about those two cases and how it changes) – Houst Sep 07 '20 at 09:39
  • @AugustKarlstrom I thought I addressed that explicitly in the answer. – Sourav Ghosh Sep 07 '20 at 10:01
1

In detail:

(stoken_t*)(0) simply casts 0 (this could be an arbitrary numeric literal) to a pointer to stoken_t, ((stoken_t*)(0)->val) is then the type of the val member of stoken_t and sizeof returns the number of bytes this type occupies in memory. In short, this expression finds the size of a struct member at compile time without the need for an instance of that struct type.

Peter
  • 2,919
  • 1
  • 16
  • 35