1

Consider the if statement: if (((DbSignal*) ev->newVal.buff)->sig)

Where DbSignal is a structure.

Why is DbSignal within brackets and what is the asterisk operator doing in this case?

IllyaKara
  • 119
  • 4

3 Answers3

3

The syntax (DbSignal*) is a typecast. It converts one type to another.

In this case, the operand of the cast is ev->newVal.buff which presumably is a pointer to a character buffer. This pointer is converted to a pointer to DbSignal via the cast. The result is then dereferenced and the sig member is accessed.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • For clarification, the ```newVal``` pointer within the structure that ```ev``` points to is having the buffer replaced with ```DbSignal``` and then ```newVal``` is being dereferenced to retrieve the ```sig``` value from ```DbSignal```? – IllyaKara Feb 10 '21 at 01:13
  • @IllyaKara It's not being replaced but reinterpreted as a different type. So the bytes that `newVal` points to are now being treated as if they are a `DbSignal`. – dbush Feb 10 '21 at 01:39
2

It is the cast: ev->newVal.buff is casted to pointer to DbSignal. Then this pointer is being dereferenced (sig member accessed)

What is the type cast: What exactly is a type cast in C/C++?

0___________
  • 60,014
  • 4
  • 34
  • 74
0

We have ev which is a pointer in this case. it points to a struct containing the variable newVal which contains a buff pointer.

So we have ev->newVal.buff

Here buff is either a char* or void* (a series of bytes, but apparently has some layout). Meaning that the memory it points to could potentially be interpreted in different ways.

By your example, we know that buff has a certain layout, corresponding to the DbSignal struct.

So in order to access ->sig we have to cast this .buff to DbSignal, basically telling that we want to interpret that memory region with the layout described by DbSignal.

Hope this gives some context.

Sad Adl
  • 35
  • 4