Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For small values of integer is the memory space is wasted

Tags:

c

memory

I Know that an integer datatype take 2 or 4 bytes of memory. I want to know that if the value of int datatype variable value is less then is the space is wasted?

#include <stdio.h>
int main(void)
{
  int a=1;
  printf("%d\n",a);
}

a binary value is 00000001 which is 1 byte, the int data type allocates 2byte of space for the a value.is the remaining 1 byte is wasted?

like image 447
ManideepVakulabharanam Avatar asked Mar 07 '23 01:03

ManideepVakulabharanam


1 Answers

In theory, yes the space is wasted. Although on a 32 bit CPU, allocating 32 bits of data might mean faster access since it suits the alignment. So using a 32 bit variable just to store the value 1 could be an optimization of speed over memory consumption.

On microcontroller systems, programmers have far less memory and are therefore more picky with variable declarations, using the types from stdint.h instead, to allocate just as much memory as needed. They would use uint8_t rather than int.

If you want the best of both worlds - fastest access and then low memory consumption if possible - use the uint_fast8_t type. Then the compiler will pick the fastest possible type that can store values up to 255.

like image 115
Lundin Avatar answered Mar 09 '23 14:03

Lundin