Search code examples
c#cassertzero

How does C assert that this struct is not equal to zero?


I am trying to understand (with my C# background) how does the following assert work for msf_s:

https://github.com/ShiftMediaProject/libcdio/blob/master/lib/driver/sector.c#L66

cdio_assert (msf != 0);

https://github.com/ShiftMediaProject/libcdio/blob/master/lib/driver/cdio_assert.h#L50

#define cdio_assert(expr) \
 assert(expr)

https://github.com/ShiftMediaProject/libcdio/blob/master/include/cdio/types.h#L217

  PRAGMA_BEGIN_PACKED
  struct msf_s {
    uint8_t m, s, f; /* BCD encoded! */
  } GNUC_PACKED;
  PRAGMA_END_PACKED

It is used in the following snippet:

lba_t
cdio_msf_to_lba (const msf_t *msf)
{
  uint32_t lba = 0;

  cdio_assert (msf != 0);

  lba = cdio_from_bcd8 (msf->m);
  lba *= CDIO_CD_SECS_PER_MIN;

  lba += cdio_from_bcd8 (msf->s);
  lba *= CDIO_CD_FRAMES_PER_SEC;

  lba += cdio_from_bcd8 (msf->f);

  return lba;
}

Basically, I need to replicate the same behavior but in C#.

Question:

Does cdio_assert sums up each field of msf_s and assert they're not equal to zero ?


Solution

  • If you take a closer look at the code you linked:

    void
    cdio_lsn_to_msf (lsn_t lsn, msf_t *msf) // <===== here
    {
      int m, s, f;
    
      cdio_assert (msf != 0);
    
      // ...
    

    You'll see that the variable msf is a pointer to a variable of type msf_t. While it does not make sense for a structure to be 0, a pointer can very well be 0, aka NULL. That line is just making sure that msf is valid before using it. Most of the times this is done with an if, but this function apparently expects the value to be valid.

    The equivalent in C# would be to assert msf != null.