POWER C does not do struct padding

A modern C compiler takes a struct data type and pads its elements to i.e. 4 or 8 bytes in order to improve CPU access times. Here is a simple example from GCC 14.2.0:

/* Testing struct padding in GCC /*
#include <stdio.h>
struct s1 {
  char a;
  int b;
  char c;
};
struct s2 {
  char a;
  char c;
  int b;
};
int main(void) {
  struct s1 sTest1 = {'a', 12, 'c'}; // Assigning values ist not
  struct s2 sTest2 = {'a', 'c', 12}; // important for the test!
  printf("Size of sTest1: %d bytes\n", sizeof(sTest1)); // 12
  printf("Size of sTest2: %d bytes\n", sizeof(sTest2)); // 8
  return(0);
} 

In this example, struct s1 has a size of 12 bytes whereas s2 has a size of 8 bytes! In other words, s1 got padded by the compiler, which added 4 bytes. Unless something like #pragma pack or __attribute__((packed)) should be used in the code, the programmer has to consider the order of the variables inside the struct in order to conserve memory space.

POWER C on the Commodore C64 does not do this. No matter in which order and of which length the elements of a struct are, the byte length is always the same. Here is the code to prove this:

/* Testing struct padding in POWER C */
#include <stdio.h>
struct s1 {
  char a;
  int b;
  char c;
};
struct s2 {
  char a;
  char c;
  int b;
};
int main(void) {
  struct s1 sTest1;
  struct s2 sTest2;
  /* Both struct data types are 4 bytes */
  printf("Size of sTest1: %d bytes\n", sizeof(sTest1));
  printf("Size of sTest2: %d bytes\n", sizeof(sTest2));
  return(0);
}

Char a is 1 byte, int b is two bytes, char c is 1 byte, for a total of 4 bytes. No matter in which order the elements are, the size of the struct is always 4 bytes. This does not change even if one exceeds the 4 or 8 byte limit. If for example another char d is added to the struct for a total of 5 bytes, the order still does not matter.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert


Der Zeitraum für die reCAPTCHA-Überprüfung ist abgelaufen. Bitte laden Sie die Seite neu.