NO

Author Topic: Declared variables ordering  (Read 320 times)

Offline John Z

  • Member
  • *
  • Posts: 840
Declared variables ordering
« on: September 12, 2024, 03:40:40 AM »
Does Pelles C compiler reorder declared procedure variables  (smallest to largest ) to minimize wasted bytes or should I be doing it manually?

John Z

Offline Vortex

  • Member
  • *
  • Posts: 841
    • http://www.vortex.masmcode.com
Re: Declared variables ordering
« Reply #1 on: September 12, 2024, 11:08:35 AM »
Hi John,

You need to take in account the alignment principle, local variables ( 32-bit ) pushed to the stack are aligned to DWORD :

Code: [Select]
#include <stdio.h>
#include <windows.h>

int main(int argc, char *argv[])
{
int x=1536;
char t=65;

        printf("x=%u , t=%c\n",x,t);

printf("sizeof x=%u ,sizeof=%u\n",sizeof(x),sizeof(t));

    return 0;
}

Output :

Code: [Select]
x=1536 , t=A
sizeof x=4 ,sizeof=1

Disassembling the object module :

Code: [Select]
_main   PROC NEAR
        push    65           ; 4 bytes
        push    1536         ; 4 bytes
        push    offset @1023
        call    _printf
        add     esp, 12
        push    1     
        push    4     
        push    offset @1025
        call    _printf     
        add     esp, 12     
        xor     eax, eax   
        ret                 
_main   ENDP

The char and int values are occupying the same size, 4 bytes ( =DWORD )
Code it... That's all...

Offline John Z

  • Member
  • *
  • Posts: 840
Re: Declared variables ordering
« Reply #2 on: September 13, 2024, 07:57:43 AM »
Thanks Vortex,

 :( I was hoping the compiler did it . . . well I've got some rearranging to do then...

Cheers,
John Z

Offline Vortex

  • Member
  • *
  • Posts: 841
    • http://www.vortex.masmcode.com
Re: Declared variables ordering
« Reply #3 on: September 13, 2024, 09:12:27 PM »
The 64-bit version :

Code: [Select]
#include <stdio.h>
#include <windows.h>

int main(int argc, char *argv[])
{
size_t x=1536;
char t=65;

        printf("x=%zu , t=%c\n",x,t);

printf("sizeof x=%zu ,sizeof t=%zu\n",sizeof(x),sizeof(t));

    return 0;
}

Output :

Code: [Select]
x=1536 , t=A
sizeof x=8 ,sizeof t=1
Code it... That's all...