NO

Author Topic: Declared variables ordering  (Read 5432 times)

Offline John Z

  • Member
  • *
  • Posts: 924
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: 907
    • 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: 924
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: 907
    • 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...

Offline HellOfMice

  • Member
  • *
  • Posts: 221
  • Never be pleased, always improve
Re: Declared variables ordering
« Reply #4 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 ;
--------------------------------
Kenavo

Offline HellOfMice

  • Member
  • *
  • Posts: 221
  • Never be pleased, always improve
Re: Declared variables ordering
« Reply #5 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
--------------------------------
Kenavo