Variable size/Set: Difference between revisions
m (Stop submissions from overlapping infobox) |
(add C example) |
||
Line 7: | Line 7: | ||
for Response'Size use 1; -- Setting the size of Response to 1 bit, rather than the default single byte size |
for Response'Size use 1; -- Setting the size of Response to 1 bit, rather than the default single byte size |
||
</lang> |
</lang> |
||
=={{header|C}}== |
|||
<lang c>#include <stdint.h> |
|||
int_least32_t foo;</lang> |
|||
Here <var>foo</var> is a signed integer with at least 32 bits. [[wp:stdint.h#Minimum-width integer types|stdint.h]] also defines minimum-width types for at least 8, 16, 32, and 64 bits, as well as unsigned integer types. |
|||
=={{header|D}}== |
=={{header|D}}== |
Revision as of 18:18, 19 May 2009
You are encouraged to solve this task according to the task description, using any language you may know.
Demonstrate how to specify the minimum size of a variable or a data type.
Ada
<lang ada> type Response is (Yes, No); -- Definition of an enumeration type with two values for Response'Size use 1; -- Setting the size of Response to 1 bit, rather than the default single byte size </lang>
C
<lang c>#include <stdint.h>
int_least32_t foo;</lang>
Here foo is a signed integer with at least 32 bits. stdint.h also defines minimum-width types for at least 8, 16, 32, and 64 bits, as well as unsigned integer types.
D
In D, any variables of static array of zero length has a size of zero. But such data is useless, as no base type element can be accessed.
<lang d>
typedef long[0] zeroLength ;
writefln(zeroLength.sizeof) ; // print 0
</lang>
NOTE: a dynamic array variable's size is always 8 bytes, 4(32-bit) for length and 4 for a reference pointer of the actual storage somewhere in runtime memory.
The proper candidates of minimum size variable are empty structure, 1-byte size data type variable (include byte, ubyte, char and bool), and void, they all occupy 1 byte.
<lang d>
byte b ;
ubyte ub ;
char c ;
bool t ;
</lang>
bool is logically 1-bit size, but it actually occupy 1 byte.
void can't be declared alone, but void.sizeof gives 1.
An empty structure is logically zero size, but still occupy 1 byte.
<lang d>
struct Empty { }
writefln(Empty.sizeof) ; // print 1
</lang>
Perl
I suppose you could use vec() or similar to twiddle a single bit. The thing is, as soon as you store this in a variable, the SV (the underlying C implementation of the most simple data type) already takes a couple dozen of bytes.
In Perl, memory is readily and happily traded for expressiveness and ease of use.