sizeof_demo.tc¶
sizeof_demo.tc — compile-time sizeof for struct types
// sizeof_demo.tc — compile-time sizeof for struct types
//
// `sizeof(StructTag)` returns the SLOT COUNT of a struct at compile time
// (folded to an integer literal at compile, zero runtime cost — no opcode
// for the operator itself, just a PUSH_IMM of the computed value).
//
// TinyC sizeof reports SLOTS, not bytes. Every scalar (int, float, char,
// bool) takes 1 slot in the VM's int32 array model. char[N] fields count
// as N slots. Nested struct fields contribute their full member slot count
// transparently.
//
// CURRENT SCOPE (1.6.x): only struct tags work.
//
// sizeof(MyStruct) ✓ → struct member slot count
// sizeof(int) ✗ parser rejects primitive type keywords
// sizeof(my_var) ✗ "unknown type 'my_var'" — variables not
// supported, only TYPE names
// sizeof(arr) ✗ same — use the array's declared size
// directly (e.g. #define NUMS_N 10)
//
// If you need array-element-count, hardcode it as a #define and check
// it manually rather than via sizeof:
// #define NUMS_N 10
// int nums[NUMS_N];
// // …loop bounds use NUMS_N directly.
struct Point {
int x; // 1 slot
int y; // 1 slot
}; // → sizeof(Point) = 2
struct Frame {
int id; // 1 slot
char label[8]; // 8 slots
float value; // 1 slot
}; // → sizeof(Frame) = 10
struct Rect {
struct Point tl; // 2 slots (nested)
struct Point br; // 2 slots
}; // → sizeof(Rect) = 4
int main() {
char line[64];
sprintf(line, "sizeof(Point) = %d slot(s)", sizeof(Point)); addLog(line); // 2
sprintf(line, "sizeof(Frame) = %d slot(s)", sizeof(Frame)); addLog(line); // 10
sprintf(line, "sizeof(Rect) = %d slot(s)", sizeof(Rect)); addLog(line); // 4
// sizeof at compile time can drive other compile-time constants —
// useful for declaring buffers of matching size:
// (Not demonstrated here because a buffer-sized-by-sizeof would
// itself need to compile against the same struct tag.)
return 0;
}