Pelles C forum

C language => Beginner questions => Topic started by: John Z on September 12, 2024, 03:40:40 AM

Title: Declared variables ordering
Post by: John Z 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
Title: Re: Declared variables ordering
Post by: Vortex 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 :

#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 :

x=1536 , t=A
sizeof x=4 ,sizeof=1


Disassembling the object module :

_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 )
Title: Re: Declared variables ordering
Post by: John Z 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
Title: Re: Declared variables ordering
Post by: Vortex on September 13, 2024, 09:12:27 PM
The 64-bit version :

#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 :

x=1536 , t=A
sizeof x=8 ,sizeof t=1
Title: Re: Declared variables ordering
Post by: HellOfMice on October 28, 2024, 10:07:38 AM
John, you can use "alignas" too, like this


#include <stdalign.h>

   alignas(HANDLE)   HANDLE    _hThread ;
   alignas(int)           int            _iIndex ;
   alignas(DWORD)   DWORD    _dwThreadId ;
Title: Re: Declared variables ordering
Post by: HellOfMice on November 26, 2024, 12:46:44 PM
JohnZ,


You can store them into a structure


It is easier if you have two variable to set to 0


Philippe