preprocessor and sizeof() question

Coding and general discussion relating to the compiler

Moderators: David Barker, Jerry Messina

Post Reply
Jerry Messina
Swordfish Developer
Posts: 1473
Joined: Fri Jan 30, 2009 6:27 pm
Location: US

preprocessor and sizeof() question

Post by Jerry Messina » Fri Feb 22, 2013 11:44 am

Is there any syntax that would let me check the sizeof() a structure at compile time?

Ideally, I'd like to do something like

Code: Select all

structure st_t
    a as byte
    b as byte
    c as byte
end structure

dim st as st_t

#if sizeof(st < 4)
  #error "structure is too small"
#endif
or

Code: Select all

#define st_size = sizeof(st_t)
but they both generate a compiler error.

I also tried

Code: Select all

const st_size = sizeof(st)        // can use sizeof() to init a const...
#if (st_size < 4)
  #error "too small"
#endif
which compiles, but doesn't work

I've tried all sorts of methods using #defines, #const, etc, but I can't come up with one that lets the preprocessor "see" compile-time program declarations.

User avatar
David Barker
Swordfish Developer
Posts: 1214
Joined: Tue Oct 03, 2006 7:01 pm
Location: Saltburn by the Sea, UK
Contact:

Post by David Barker » Fri Feb 22, 2013 4:11 pm

No, there is not a way to determine the sizeof() a structure or variable during pre-processing (as they do not exists to the compiler at that point in time). You can obviously bring pre-processor values into a program, but not the other way around.

Jerry Messina
Swordfish Developer
Posts: 1473
Joined: Fri Jan 30, 2009 6:27 pm
Location: US

Post by Jerry Messina » Fri Feb 22, 2013 4:33 pm

That's what I figured.

I came up with a way of checking at compile time that I set the #define correctly...

Code: Select all

include "system.bas"

structure st_t
    a as byte
    b as byte
    c as byte
end structure

dim st as st_t

// this has to be set manually
// if sizeof(st_t) changes, so must it
#define SIZEOF_ST = 3               // sizeof(st_t) = 3

// define a macro that we can use to check the above
macro check_sizeof_st()
  const _sizeof_st = SIZEOF_ST    
  if (_sizeof_st <> sizeof(st_t)) then
      CheckParam(etError, "#define SIZEOF_ST must be adjusted")
  endif
end macro

// compile-time check
check_sizeof_st()
At least this way I know if I have to change it.

Post Reply