Variable size/Get: Difference between revisions

add RPL
m (removed stray text in 'omit from' list)
(add RPL)
 
(35 intermediate revisions by 24 users not shown)
Line 1:
{{task|Type System}}
{{omit from|AWK}}
{{omit from|Clojure}}
{{omit from|E}}
{{omit from|gnuplot}}
{{omit from|Groovy}}
{{omit from|GUISS|Does not have variables.}}
{{omit from|Java}}
{{omit from|JavaScript}}
{{omit from|LaTeX}}
{{omit from|Logtalk}}
{{omit from|Make}}
{{omit from|Maxima}}
{{omit from|NetRexx}}
{{omit from|PlainTeX}}
{{omit from|XSLT}}
{{omit from|Unlambda|Does not have variables.}}
 
Demonstrate how to get the size of a variable.
 
See also: [[Host introspection]]
 
=={{header|11l}}==
<syntaxhighlight lang="11l">Int64 i
print(T(i).size)
print(Int64.size)</syntaxhighlight>
 
{{out}}
<pre>
8
8
</pre>
 
=={{header|ActionScript}}==
Requires the debug Flash Player 9.0.115.0 or higher.
<syntaxhighlight lang="actionscript">
<lang ActionScript>
package {
Line 56 ⟶ 51:
 
}
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
Ada represents the size of a variable in bits, not bytes like many other languages.
<langsyntaxhighlight lang="ada">Int_Bits : constant Integer := Integer'size;
Whole_Bytes : constant Integer := Int_Bits / Storage_Unit; -- Storage_Unit is the number of bits per storage element</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 73 ⟶ 68:
 
Also note that the size of a '''byte''' can vary from one [[wp:CPU|CPU]] to another, c.f. [[Host_introspection#ALGOL_68]] for additional details.
<langsyntaxhighlight lang="algol68">INT i; BYTES b; # typically INT and BYTES are the same size #
STRING s:="DCLXVI", [666]CHAR c;
print((
Line 79 ⟶ 74:
"UPB STRING s =",UPB s, new line,
"UPB []CHAR c =",UPB c, new line
))</langsyntaxhighlight>
{{out}}
<pre>
Line 88 ⟶ 83:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">VarSetCapacity(Var, 10240000) ; allocate 10 megabytes
MsgBox % size := VarSetCapacity(Var) ; 10240000</langsyntaxhighlight>
 
=={{header|Babel}}==
In Babel, you can get the raw size with the mu operator and you can also
break this down into its components:
<langsyntaxhighlight lang="babel">main:
{ (1 2 (3 4) 5 6)
dup mu disp
Line 105 ⟶ 100:
 
disp! : { %d cr << }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 131 ⟶ 126:
You can also take the size of an object by first serializing it:
 
<langsyntaxhighlight lang="babel">main : { (1 2 (3 4) 5 6) unload size %d << }
</syntaxhighlight>
</lang>
{{out}}
38
 
=={{header|BASIC}}==
<langsyntaxhighlight lang="gwbasic">10 REM this only works with strings
20 PRINT LEN(variable$)</langsyntaxhighlight>
 
{{works with|QBasic}}
Line 144 ⟶ 139:
Many BASICs, especially those compatible with [[QBasic]],
can use <code>LEN</code> to find the size of any variable:
<langsyntaxhighlight lang="qbasic">DIM a AS INTEGER, b AS LONG, c AS SINGLE, d AS DOUBLE, e AS STRING
PRINT LEN(a), LEN(b), LEN(c), LEN(d), LEN(e)</langsyntaxhighlight>
 
{{out}}
Line 152 ⟶ 147:
Note that when used with a string, <code>LEN</code> reports the length of the string, not its size in memory.
BASIC typically stores information about the string separately from the string itself, usually immediately before the string itself in memory (but some implementations may store such information elsewhere).
 
==={{header|Applesoft BASIC}}===
Simple (non-array) real, integer, or string variables use 7 bytes including the 2 bytes for the variable name. Real variables use all 5 bytes for the value: a 1 byte exponent, and a 4 byte mantissa. Integer variables use 2 bytes for the value, and have 0's in the remaining 3 bytes. String variables use 3 bytes: 1 byte for the length of the string, 2 bytes for the pointer to the string in memory, and have 0's in the remaining 2 bytes.
 
Functions use 2 bytes for the pointer to the function definition in the program, 2 bytes for the pointer to the argument, a 1 byte copy of the first character of the function definition, and 7 bytes to store the argument variable.
 
To get the size of the variable, determine the type of the last variable used. The sizes reported do not include the 2 bytes to store the variable name. The sizes of array values are only for the specific value within an array.
<syntaxhighlight lang="gwbasic"> 100 PRINT "SIZE OF INTEGER I% IS ";:I% = I%: GOSUB 240
110 PRINT "SIZE OF FLOAT I IS ";:I = I: GOSUB 240
120 PRINT "SIZE OF STRING I$ IS ";:I$ = I$: GOSUB 240
130 PRINT " LEN OF STRING I$ IS " LEN (I$)
140 PRINT "SIZE OF FLOAT ARG N IS ";: DEF FN I(N) = 0: GOSUB 240
150 PRINT "SIZE OF FUNCTION FN I IS ";: PRINT MID$ ( STR$ ( FN I(0)),1,0);: GOSUB 240
160 PRINT "ARRAYS:"
170 PRINT "SIZE OF FLOAT I(1) IS ";:I(1) = I(1): GOSUB 240
180 PRINT "SIZE OF INTEGER I%(2) IS ";:I%(2) = I%(2): GOSUB 240
190 PRINT "SIZE OF STRING I$(3) IS ";:I$(3) = I$(3): GOSUB 240
200 PRINT " LEN OF STRING I$(3) IS " LEN (I$(3))
210 PRINT "SIZE OF STRING I$(4) IS ";:I$(4) = "HELLO, WORLD!": GOSUB 240
220 PRINT " LEN OF STRING I$(4) IS " LEN (I$(4))
230 END
240 GOSUB 250: PRINT PEEK (236) + PEEK (237) * 256: RETURN
250 POKE 236,12: POKE 237,0: IF PEEK (129) > 127 AND PEEK (130) < 128 THEN RETURN
260 POKE 236,5
270 IF PEEK (129) < 128 AND PEEK (130) > 127 GOTO 310STR
280 IF PEEK (131) + PEEK (132) * 256 < PEEK (107) + PEEK (108) * 256 THEN RETURN
290 IF PEEK (129) < 128 AND PEEK (130) < 128 THEN RETURN
300 POKE 236,2: IF PEEK (129) > 127 AND PEEK (130) > 127 THEN RETURN
310 IF PEEK (131) + PEEK (132) * 256 > = PEEK (107) + PEEK (108) * 256 THEN POKE 236,3
320 IF PEEK ( PEEK (131) + PEEK (132) * 256) + PEEK (236) > 255 THEN POKE 237,1: POKE 236, PEEK ( PEEK (131) + PEEK (132) * 256) + PEEK (236) - 256: RETURN
330 POKE 236, PEEK ( PEEK (131) + PEEK (132) * 256) + PEEK (236)
340 RETURN</syntaxhighlight>
{{out}}
<pre>
SIZE OF INTEGER I% IS 5
SIZE OF FLOAT I IS 5
SIZE OF STRING I$ IS 5
LEN OF STRING I$ IS 0
SIZE OF FLOAT ARG N IS 5
SIZE OF FUNCTION FN I IS 12
ARRAYS:
SIZE OF FLOAT I(1) IS 5
SIZE OF INTEGER I%(2) IS 2
SIZE OF STRING I$(3) IS 3
LEN OF STRING I$(3) IS 0
SIZE OF STRING I$(4) IS 16
LEN OF STRING I$(4) IS 13
</pre>
 
=={{header|BASIC256}}==
<code>TypeOf</code> returns a number representing the type of value that was passed:
 
<syntaxhighlight lang="basic256">i = 1 #Integer
f = 1.0 #Float
s$ = "cad" #String
dim a(99) #Array
A = {1, 2, 3} #Anonymous array
m = {"key" -> 1} #Map
 
print typeof(i) # 1
print typeof(f) # 2
print typeof(s$) # 3
print typeof(A) # 4
print typeof(m) # 6</syntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
A variable's size is implied by its type suffix. The easiest way to determine the size is to use a structure:
<langsyntaxhighlight lang="bbcbasic"> DIM bstruct{b&}
DIM istruct{i%}
DIM fstruct{f}
Line 166 ⟶ 225:
PRINT "Size of f is ";DIM(fstruct{})
PRINT "Size of d# is ";DIM(dstruct{})
PRINT "Size of s$ is ";DIM(sstruct{})</langsyntaxhighlight>
Here the size given for the string s$ is for its descriptor, not its contents.
 
Line 179 ⟶ 238:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">printf("An int contains %u bytes.\n", sizeof(int));</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
class Program
{
Line 192 ⟶ 251:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
Store the size of an int in bytes:
 
<langsyntaxhighlight lang="cpp">#include <cstdlib>
std::size_t intsize = sizeof(int);</langsyntaxhighlight>
 
Note: sizeof can be used without the header <cstdlib>; the latter is only needed for the type std::size_t, which is an alias for whatever type is used to store sizes for the given compiler.
 
Output the number of bits of an int:
<langsyntaxhighlight lang="cpp">#include <climits>
#include <cstdlib>
std::size_t intbits = CHAR_BITS*sizeof(int);</langsyntaxhighlight>
 
Note: the type char is always 1 byte (which, however, need not be 8 bits).
Line 211 ⟶ 270:
Get the size of a variable in bytes:
 
<langsyntaxhighlight lang="cpp">#include <cstdlib>
int a = 1;
std::size_t a_size = sizeof a;</langsyntaxhighlight>
 
Note: Parentheses are needed around types, but not around variables.
Line 219 ⟶ 278:
Get the size of an expression's type:
 
<langsyntaxhighlight lang="cpp">#include <cstdlib>
std::size_t size = sizeof (3*6 + 7.5);</langsyntaxhighlight>
 
=={{header|COBOL}}==
Line 244 ⟶ 303:
Directing Facility <code>>>IF P64 IS SET</code>, shown here.
{{works with|GnuCOBOL}}
<syntaxhighlight lang="cobol">
<lang COBOL>
identification division.
program-id. variable-size-get.
Line 306 ⟶ 365:
goback.
end program variable-size-get.
</syntaxhighlight>
</lang>
 
{{out}}
Line 366 ⟶ 425:
{{works with|LispWorks}}
 
<langsyntaxhighlight lang="lisp">(let ((a (cons 1 2))
(b (make-array 10))
(c "a string"))
(list (hcl:find-object-size a)
(hcl:find-object-size b)
(hcl:find-object-size c)))</langsyntaxhighlight>
returns
 
<syntaxhighlight lang ="lisp">(12 48 24)</langsyntaxhighlight>
 
However, note that interesting objects are generally composed of several levels of references, often including references to preexisting objects, so what the size should be considered as is often hard to define after the fact. A robust though non-automatic way to determine the “true” memory utilization of some data is to do something like this:
 
<langsyntaxhighlight lang="lisp">(let (items)
(gc) ; name varies by implementation
(room)
Line 384 ⟶ 443:
(push (allocate-something-of-interest) items))
(gc)
(room))</langsyntaxhighlight>
 
[http://www.lispworks.com/documentation/HyperSpec/Body/f_room.htm room] prints information about current memory usage, but in an implementation-defined format. Take the difference of the relevant numbers, divide by 512, and you have the amount of memory consumed by allocating one additional instance of whatever it is.
Line 390 ⟶ 449:
=={{header|D}}==
Every type and variable in D has a property <tt>sizeof</tt>, which give the size of the type in bytes. eg.
<langsyntaxhighlight lang="d">int i ;
writefln(i.sizeof) ; // print 4
int[13] ints1 ; // static integer array of length 13
Line 396 ⟶ 455:
int[] ints2 = new int[13] ; // dynamic integer array, variable length, currently 13
writefln(ints2.sizeof) ; // print 8, all dynamic array has this size
writefln(ints2.length) ; // print 13, length is the number of allocated element in aggregated type</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">i := sizeof([{any variable or structure]data type identifier});</langsyntaxhighlight>
 
=={{header|Elixir}}==
When “counting” the number of elements in a data structure, Elixir also abides by a simple rule: the function is named '''size''' if the operation is in constant time or '''length''' if the operation is linear.
<langsyntaxhighlight lang="elixir">list = [1,2,3]
IO.puts length(list) #=> 3
 
Line 424 ⟶ 483:
 
map = Map.new([{:b, 1}, {:a, 2}])
IO.puts map_size(map) #=> 2</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 437 ⟶ 496:
2
</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: layouts memory prettyprint ;
 
! Show size in bytes
{ 1 2 3 } size . ! 48
1231298302914891021239102 size . ! 48
 
! Doesn't work on fixnums and other immediate objects
10 size . ! 0
 
! Show number of bits in a fixnum
fixnum-bits . ! 60</syntaxhighlight>
 
=={{header|Forth}}==
{{works with|ANS/ISO Forth}}
Forth is very close to the metal. Forth 94 standardized the size of an integer to be the native integer size of the CPU. Forth refers to this as a CELL. The defining word VARIABLE creates a variable that is one cell wide. The word CELLS takes an integer parameter and returns the number of bytes in one CELL.
<syntaxhighlight lang="forth">: .CELLSIZE ( -- ) CR 1 CELLS . ." Bytes" ;
VARIABLE X ( creates a variable 1 cell wide)</syntaxhighlight>
Test at the GNU Forth (32bit) console
<syntaxhighlight lang="forth">.CELLSIZE
4 Bytes ok
-1 X ! ok
HEX X @ U. FFFFFFFF ok</syntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
The intrinsic functions bit_size and digits can be used to find the size of an integer. Bit_size returns the number of bits in an integer while digits returns the number of significant digits in the integer. Because of the use of signed intergersintegers this will be one less than the bit size. Digits can be used on real variables where it returns the number of significant figures in the mantissa.
<langsyntaxhighlight lang="fortran">INTEGER, PARAMETER :: i8 = SELECTED_INT_KIND(2)
INTEGER, PARAMETER :: i16 = SELECTED_INT_KIND(4)
INTEGER, PARAMETER :: i32 = SELECTED_INT_KIND(8)
Line 454 ⟶ 537:
WRITE (*,*) BIT_SIZE(fourbytes), DIGITS(fourbytes) ! prints 32 and 31
WRITE (*,*) BIT_SIZE(eightbytes), DIGITS(eightbytes) ! prints 64 and 63
WRITE (*,*) DIGITS(0.0), DIGITS(0d0) ! prints 24 and 53</langsyntaxhighlight>
 
=={{header|Free Pascal}}==
The FPC (Free Pascal compiler) supports the UCSD Pascal extension <tt>sizeOf</tt>.
See [[#Delphi|Delphi]] for an example.
It can be used in compile-time expressions, too.
Furthermore, the GNU Pascal extension <tt>bitSizeOf</tt> is available, too, which is particularly interesting for <tt>packed</tt> structures’ members.
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim i As Integer
Line 477 ⟶ 566:
Print "Press any key to quit"
Sleep
</syntaxhighlight>
</lang>
 
{{out}}
Line 488 ⟶ 577:
A single occupies 4 bytes
A double occupies 8 bytes
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
void local fn Doit
NSLog(@"%ld",sizeof(long))
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
{{out}}
<pre>
8
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=87f102023bd9ef6dbd52b0158be2c3ee Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
 
Print "Boolean =\t " & SizeOf(gb.Boolean)
Line 507 ⟶ 613:
Print "Variant =\t " & SizeOf(gb.Variant)
 
End</langsyntaxhighlight>
Output:
<pre>
Line 525 ⟶ 631:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">import "unsafe"
 
unsafe.Sizeof(x)</langsyntaxhighlight>
More detail:
<langsyntaxhighlight lang="go">package main
 
import (
Line 553 ⟶ 659:
// Some sizes are implementation dependent.
fmt.Println(runtime.Version(), runtime.GOARCH)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 565 ⟶ 671:
=={{header|Haskell}}==
only works with types that instance Storable:
<langsyntaxhighlight lang="haskell">import Foreign
 
sizeOf (undefined :: Int) -- size of Int in bytes (4 on mine)
sizeOf (undefined :: Double) -- size of Double in bytes (8 on mine)
sizeOf (undefined :: Bool) -- size of Bool in bytes (4 on mine)
sizeOf (undefined :: Ptr a) -- size of Ptr in bytes (4 on mine)</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 582 ⟶ 688:
** This will show 0 for the assignment of program constants such as strings. Manipulation will be required to produce an allocation.
 
<langsyntaxhighlight Iconlang="icon">record rec0()
record rec4(a,b,c,d)
 
Line 610 ⟶ 716:
write("type=",type(x)," *x=",*x," bytes allocated=",a1-a0)
}
end</langsyntaxhighlight>
 
{{out}}
Line 633 ⟶ 739:
IDL is array based, so its <tt>size()</tt> function is geared towards that:
 
<langsyntaxhighlight lang="idl">arr = intarr(3,4)
print,size(arr)
;=> prints this:
2 3 4 2 12</langsyntaxhighlight>
 
The result means: 2 dimensions in the array, the first dimension has extent 3, the second has extent 4, the elements of the array are 2-byte integers (IDL's default for an "int"), there's a total of 12 elements in the array.
Line 645 ⟶ 751:
 
For example:
<langsyntaxhighlight lang="j">some_variable =: 42
7!:5<'some_variable'</langsyntaxhighlight>
An advantage of <code>7!:5</code> is that it can be used on any name, including functions, operators, etc (i.e. it's not just restricted to variables):
<langsyntaxhighlight lang="j">some_function =: +/ % #
7!:5<'some_function'</langsyntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
public final class VariableSize {
 
public static void main(String[] aArgs) {
System.out.println("A Byte variable occupies: " + Byte.SIZE / 8 + " byte");
System.out.println("A Char variable occupies: " + Character.SIZE / 8 + " bytes");
System.out.println("A Short variable occupies: " + Short.SIZE / 8 + " bytes");
System.out.println("A Float variable occupies: " + Float.SIZE / 8 + " bytes");
System.out.println("An Integer variable occupies: " + Integer.SIZE / 8 + " bytes");
System.out.println("A Double variable occupies: " + Double.SIZE / 8 + " bytes");
System.out.println("A Long variable occupies: " + Long.SIZE / 8 + " bytes");
}
 
}
</syntaxhighlight>
{{ out }}
<pre>
A Byte variable occupies: 1 byte
A Char variable occupies: 2 bytes
A Short variable occupies: 2 bytes
A Float variable occupies: 4 bytes
An Integer variable occupies: 4 bytes
A Double variable occupies: 8 bytes
A Long variable occupies: 8 bytes
</pre>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">julia> sizeof(Int8)
1
 
Line 659 ⟶ 792:
 
julia> sizeof(t)
8</langsyntaxhighlight>
(The last line returns 4 on a 32-bit machine or when Julia is compiled in 32-bit mode.)
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun main(args: Array<String>) {
Line 674 ⟶ 807:
println("A Double variable occupies: ${java.lang.Double.SIZE / 8} bytes")
println("A Char variable occupies: ${java.lang.Character.SIZE / 8} bytes")
}</langsyntaxhighlight>
 
{{out}}
Line 688 ⟶ 821:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(
mystring = 'Hello World',
myarray = array('one', 'two', 3),
Line 709 ⟶ 842:
//#myinteger -> size // will fail
// an integer can however be converted to a string first
string(#myinteger) -> size</langsyntaxhighlight>
->11
 
Line 717 ⟶ 850:
 
4
=={{header|Lua}}==
<syntaxhighlight lang="lua">> s = "hello"
> print(#s)
5
> t = { 1,2,3,4,5 }
> print(#t)
5</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ByteCount["somerandomstring"]</langsyntaxhighlight>
 
{{out}}
<pre>64</pre>
Line 727 ⟶ 866:
BITSIZE and BYTESIZE are built in functions.
 
<langsyntaxhighlight lang="modula3">MODULE Size EXPORTS Main;
 
FROM IO IMPORT Put;
Line 735 ⟶ 874:
Put("Integer in bits: " & Int(BITSIZE(INTEGER)) & "\n");
Put("Integer in bytes: " & Int(BYTESIZE(INTEGER)) & "\n");
END Size.</langsyntaxhighlight>
 
{{out}}
Line 744 ⟶ 883:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">echo "An int contains ", sizeof(int), " bytes."</langsyntaxhighlight>
 
=={{header|NS-HUBASIC}}==
Note: This only works with strings.
<syntaxhighlight lang="ns-hubasic">10 PRINT LEN(VARIABLE$)</syntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">(** The result is the size given in word.
The word size in octet can be found with (Sys.word_size / 8).
(The size of all the datas in OCaml is at least one word, even chars and bools.)
Line 771 ⟶ 914:
in
fst(rec_size [] (Obj.repr v))
;;</langsyntaxhighlight>
 
testing in the toplevel:
<langsyntaxhighlight lang="ocaml"># sizeof 234 ;;
- : int = 1
 
Line 858 ⟶ 1,001:
 
# sizeof(Array.init 10 (fun _ -> String.create 20)) ;;
- : int = 61</langsyntaxhighlight>
 
=={{header|Odin}}==
 
<syntaxhighlight lang="odin">package main
 
import "core:fmt"
 
main :: proc() {
fmt.println("An int contains", size_of(int), "bytes.")
}</syntaxhighlight>
 
=={{header|Ol}}==
The 'size' function returns size of allocated memory buffer assigned to variable. For regular objects (that always a references to real object in heap) like vectors and pairs it returns size of object in virtual machine words (the object header not counts). For 'raw' objects (a bitstreams like vm bytecode and ansi strings) in returns size of object in native machine bytes.
 
For values (like small numbers and constants) it returns #false.
 
=={{header|ooRexx}}==
Line 869 ⟶ 1,027:
=={{header|PARI/GP}}==
In GP, this gets the size of the variable x in bytes:
<syntaxhighlight lang ="parigp">sizebyte(x)</langsyntaxhighlight>
 
In PARI,
<syntaxhighlight lang C="c">lg(x)</langsyntaxhighlight>
returns the length of the variable x in words. <code>gsizebyte</code> and <code>gsizeword</code> are also available.
 
=={{header|Pascal}}==
Pascal discourages the programmer to care about specific data sizes.
same as Delphi:
Nevertheless [[#Delphi|Delphi]], [[#Free Pascal|FPC]] and GPC (GNU Pascal compiler) among other compilers support the UCSD Pascal extension <tt>sizeOf</tt>.
<lang delphi>i := sizeof([any variable or structure]);</lang>
 
=={{header|Perl}}==
{{works with|Perl|5.x28}}
{{libheader|Devel::Size}}
<langsyntaxhighlight lang="perl">use Devel::Size qw(size total_size);
 
my $var = 9384752;
my @arr = (1, 2, 3, 4, 5, 6);
print size($var); # 24
print total_size(\@arr); # 256</langsyntaxhighlight>
=={{header|Perl 6}}==
Perl 6 tries to avoid generic terms such as "size" and "length", instead providing methods that are expressed in terms of the units appropriate to the abstraction level.
<lang perl6># Textual strings are measured in characters (graphemes)
my $string = "abc";
 
# Arrays are measured in elements.
say $string.chars; # 3
my @array = 1..5;
say @array.elems; # 5
 
# Buffers may be viewed either as a byte-string or as an array of elements.
my $buffer = '#56997; means "four dragons".'.encode('utf8');
say $buffer.bytes; # 26
say $buffer.elems; # 26</lang>
Perl's Int type is arbitrary sized, and therefore the abstract size of the integer depends on how many bits are needed to represent it. While the internal representation is likely to be "chunky" by 32 or 64 bits, this is considered an implementation detail and is not revealed to the programmer.
 
Native types such as int64 or num32 are of fixed size; Perl 6 supports representational polymorphism of such types (and compositions of such types) through a pluggable meta-object protocol providing "knowhow" objects for the various representations. Currently the NativeHOW knowhow may be interrogated for the bit sizes of native types, but this is officially outside the purview of the language itself (so far).
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>printf(1,"An integer contains %d bytes.\n", machine_word())</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"An integer contains %d bytes.\n"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">machine_word</span><span style="color: #0000FF;">())</span>
<!--</syntaxhighlight>-->
See builtins\VM\pHeap.e for the complete low-level details. Because of shared references,
it is often not practical to obtain a meaningful size, and you can often store a "sparse"
Line 925 ⟶ 1,068:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
put skip list (SIZE(x)); /* gives the number of bytes occupied by X */
/* whatever data type or structure it is. */
Line 934 ⟶ 1,077:
/* varying-length string, including its */
/* length field. */
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
Line 942 ⟶ 1,085:
Form user point of view more important is space taken by values (size of values referenced by a single variable typically varies during program execution). The datasize function gives amount (in machine words) of space directly used by given value:
 
<langsyntaxhighlight lang="pop11">;;; Prints 0 because small integers need no heap storage
datasize(12) =>
;;; Prints 3: 3 character fits into single machine word, 1 word
Line 951 ⟶ 1,094:
datasize({1 2 3}) =>
;;; Prints 3 because only first node counts
datasize([1 2 3]) =></langsyntaxhighlight>
 
Note that large amount of data my be referenced from given value, but this data is potentially shared, so there is no canonical way to assign it to a single value or variable.
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Define a
Debug SizeOf(a)
; This also works for structured variables</langsyntaxhighlight>
 
=={{header|Python}}==
This information is only easily available for the array type:
<langsyntaxhighlight lang="python">>>> from array import array
>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'),
('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]
Line 976 ⟶ 1,119:
array('l', [1, 2, 3, 4, 5]) Size = 20
array('d', [1.0, 2.0, 3.1400000000000001]) Size = 24
>>></langsyntaxhighlight>
Also:
{{works with|Python|2.6+}}
<langsyntaxhighlight lang="python">import sys
sys.getsizeof(obj)</langsyntaxhighlight>
 
=={{header|R}}==
object.size gives '''an estimate''' of the amount of memory used to store the variable, in (kilo/Mega/Giga) bytes. See also dim, length and nchar for determining the extent of mulitdimensional variables (such as matrices, lists, etc).
<langsyntaxhighlight Rlang="r"># Results are system dependent
num <- c(1, 3, 6, 10)
object.size(num) # e.g. 56 bytes
Line 997 ⟶ 1,140:
 
l2 <- list(num, num2)
object.size(l2) # e.g. 128 bytes</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require ffi/unsafe)
Line 1,006 ⟶ 1,149:
(begin (printf "sizeof(~a) = ~a\n" 't (ctype-sizeof t)) ...))
(sizes _byte _short _int _long _llong _float _double)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
Raku tries to avoid generic terms such as "size" and "length", instead providing methods that are expressed in terms of the units appropriate to the abstraction level.
<syntaxhighlight lang="raku" line># Textual strings are measured in characters (graphemes)
my $string = "abc";
 
# Arrays are measured in elements.
say $string.chars; # 3
my @array = 1..5;
say @array.elems; # 5
 
# Buffers may be viewed either as a byte-string or as an array of elements.
my $buffer = '#56997; means "four dragons".'.encode('utf8');
say $buffer.bytes; # 26
say $buffer.elems; # 26</syntaxhighlight>
Raku's Int type is arbitrary sized, and therefore the abstract size of the integer depends on how many bits are needed to represent it. While the internal representation is likely to be "chunky" by 32 or 64 bits, this is considered an implementation detail and is not revealed to the programmer.
 
Native types such as int64 or num32 are of fixed size; Raku supports representational polymorphism of such types (and compositions of such types) through a pluggable meta-object protocol providing "knowhow" objects for the various representations. Currently the NativeHOW knowhow may be interrogated for the bit sizes of native types, but this is officially outside the purview of the language itself (so far).
 
=={{header|REXX}}==
In REXX, you simply set a variable to a value (it could be an expression);
<br>the value's length is the size of the variable's value.
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates (see the penultimate statement) how to */
/* to find the size (length) of the value of a REXX variable. */
 
Line 1,070 ⟶ 1,232:
│ The "k" loop uses 21,777,792 bytes for the compound variables, │
│ (excluding the DO loop indices [j and k] themselves). │
└────────────────────────────────────────────────────────────────────┘*/</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
list1 = list(2)
list2 = list(4)
Line 1,085 ⟶ 1,247:
see "Size of list4 is : " + len(list4) + nl
see "Size of list5 is : " + len(list5) + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,093 ⟶ 1,255:
Size of list4 is : 7
Size of list5 is : 5
</pre>
 
=={{header|RPL}}==
Introduced only in 2003, the <code>BYTES</code> command returns both the checksum and the size of an object. Before, Hewlett-Packard provided a table in the user manual to do the math by yourself. Size can be not an integer, as objects are made of nibbles.
{{Works with|HP|49}}
« BYTES NIP » '<span style="color:blue">OBJSIZE</span>' STO
 
42 <span style="color:blue">OBJSIZE</span>
{ 1 2 3 "FOUR" (5,6) [7 8] } <span style="color:blue">OBJSIZE</span>
« BYTES NIP » <span style="color:blue">OBJSIZE</span>
{{out}}
<pre>
3: 6.5
2: 50
1: 20.5
</pre>
 
Line 1,098 ⟶ 1,275:
Almost all objects in Ruby (MRI) take 40 bytes (on a x64 machine) initially. Sometimes this is enough to store the entire object, sometimes additional memory has to be allocated. For strings that is the case if they are longer than 23 chars. The additional memory can be retrieved using 'ObjectSpace':
 
<langsyntaxhighlight lang="ruby">
require 'objspace'
 
Line 1,104 ⟶ 1,281:
p ObjectSpace.memsize_of("a"*24) #=> 25
p ObjectSpace.memsize_of("a"*1000) #=> 1001
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::mem;
 
fn main() {
// Specify type
assert_eq!(4, mem::size_of::<i32>());
// Provide a value
let arr: [u16; 3] = [1, 2, 3];
assert_eq!(6, mem::size_of_val(&arr));
}
</syntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight Scalalang="scala"> def nBytes(x: Double) = ((Math.log(x) / Math.log(2) + 1e-10).round + 1) / 8
 
val primitives: List[(Any, Long)] =
Line 1,115 ⟶ 1,305:
(Long, Long.MaxValue))
 
primitives.foreach(t => println(f"A Scala ${t._1.toString.drop(13)}%-5s has ${nBytes(t._2)} bytes"))</langsyntaxhighlight>
{{out}}
<pre>A Scala Byte has 1 bytes
Line 1,123 ⟶ 1,313:
 
=={{header|Swift}}==
<syntaxhighlight lang ="swift">sizeofValue(x)</langsyntaxhighlight>
More detail:
<langsyntaxhighlight lang="swift">// sizeof and sizeofValue return the size in bytes.
println(sizeof(Int))
var i: Int = 42
Line 1,133 ⟶ 1,323:
// the same number, the size of the String struct.
println(sizeofValue("Rosetta"))
println(sizeofValue("Code"))}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,144 ⟶ 1,334:
=={{header|Tcl}}==
Since all variables are ultimately strings in Tcl, this is easy:
<syntaxhighlight lang ="tcl">string bytelength $var</langsyntaxhighlight>
There is additional overhead per value and per variable, which depends on the architecture that Tcl was built for and the version of Tcl. In 8.5 on a ILP-32 architecture, local variables have an overhead of 8 bytes (without traces) and values have a minimum overhead of 24 bytes (this minimum is achieved for integers that fit in a signed 64-bit integer type or a double-precision float).
 
Line 1,152 ⟶ 1,342:
There are two primary data types in Toka, cells and characters. The size of these can be obtained easily:
 
<langsyntaxhighlight lang="toka">char-size .
cell-size .</langsyntaxhighlight>
 
If you load the floating point support, you can also obtain the size of a floating point number:
 
<langsyntaxhighlight lang="toka">needs floats
float-size .</langsyntaxhighlight>
 
All sizes are returned in bytes.
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT,{}
string="somerandomstring"
Line 1,172 ⟶ 1,362:
PRINT "has size: ",size
PRINT "and length: ",length
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,181 ⟶ 1,371:
 
=={{header|TXR}}==
====Lisp Object Size====
All Lisp values are pointer-sized cells, so they have a basic size that is four or eight bytes, depending on whether the processor architecture is 32 or 64 bits. Heap values take up a four-cell record. And some objects have additional dynamically allocated memory. The <code>prof</code> operator can be wrapped around code which constructs and returns an object to calculate the size of the heap part plus dynamically allocated memory:
 
Line 1,208 ⟶ 1,398:
"foobar"</pre>
 
====FFI====
 
In the FFI type system, the <code>sizeof</code> macro operator reports size of types.
Line 1,226 ⟶ 1,416:
The <code>struct</code> size corresponds to the size of the C struct
 
<langsyntaxhighlight lang="c">struct foo {
uint32_t x : 17;
uint8_t y : 3;
char z[16];
};</langsyntaxhighlight>
 
as calculated by the GNU C compiler on the same platform. The `uint32_t` leading bitfield creates a minimum alignment of four bytes. The `y` bitfield is packed into the third byte of the structure, and the `z` array starts on the fourth, ending on the nineteenth. The alignment requirement pads the structure to 20.
Line 1,242 ⟶ 1,432:
The leading bitfield is now deemed to be byte aligned, so the structure is no longer padded for the sake of its alignment.
 
====Variable Size====
 
Since the task is worded as being about '''variables''' rather than objects, what we can do is explore the memory costs of a lexical environment.
Line 1,258 ⟶ 1,448:
=={{header|UNIX Shell}}==
 
<langsyntaxhighlight lang="sh"># In the shell all variables are stored as strings, so we use the same technique
# as for finding the length of a string:
greeting='Hello, world!'
greetinglength=`printf '%s' "$greeting" | wc -c`
echo "The greeting is $greetinglength characters in length"</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 1,278 ⟶ 1,468:
and returns the number of bits of precision in the mantissa.
Host memory usage is linear plus a small constant.
<langsyntaxhighlight Ursalalang="ursala">#import std
 
#cast %nL
 
examples = <weight 'hello',mpfr..prec 1.0E+0></langsyntaxhighlight>
{{out}}
<pre>
Line 1,289 ⟶ 1,479:
 
=={{header|Vala}}==
<syntaxhighlight lang="vala">void main(){
<lang vala>
/* you can replace the int below with any of the vala supported datatypes
void main(){
see the vala documentation for valid datatypes.
ulong x = sizeof(int); // returns # of bytes used to store an int
*/
// is returned as a ulong, but could be typecasted to int with: int x = (int) sizeof(int)
stdout.printfprint(@"%lu$(sizeof(int))\n", x);
}</syntaxhighlight>
}
 
</lang>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">sizeof(i64)</syntaxhighlight>
{{out}}
<pre>8</pre>
 
=={{header|Wren}}==
In Wren all variables have a size of 8 bytes though there is a larger, slower representation which is used for debugging the virtual machine. Consequently, no ''sizeof'' function (or similar) is needed.
 
Numbers, booleans and the special value ''null'' are stored directly within the variable's storage location using a technique known as ''NaN tagging'' and are therefore unboxed. For everything else (strings, class instances, lists etc.) the variable's storage location stores a pointer to where the actual data resides on the heap.
 
=={{header|Yabasic}}==
<code>frnfn_size</code> return the size (in bytes) of one of the types available for foreign function calls.
<syntaxhighlight lang="yabasic">print frnfn_size("uint8") //1
print frnfn_size("int8") //1
print frnfn_size("uint16") //2
print frnfn_size("int16") //2
print frnfn_size("uint32") //4
print frnfn_size("int32") //4
print frnfn_size("uint64") //8
print frnfn_size("int64") //8
print frnfn_size("float") //4
print frnfn_size("double") //8
print frnfn_size("char") //1
print frnfn_size("int") //4
print frnfn_size("short") //2</syntaxhighlight>
 
=={{header|XPL0}}==
Line 1,309 ⟶ 1,524:
for dynamic integer arrays using the Reserve intrinsic.
 
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int Size;
int A, B;
Line 1,317 ⟶ 1,532:
Size:= addr Y - addr X;
IntOut(0, Size); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 1,326 ⟶ 1,541:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">(123).len() //-->1 (byte)
(0).MAX.len() //-->8 (bytes), ie the max number of bytes in an int
(1.0).MAX.len() //-->8 (bytes), ie the max number of bytes in an float
Line 1,333 ⟶ 1,548:
Dictionary("1",1, "2",2).len() //-->2 (keys)
Data(0,Int,1,2,3,4).len() //-->4 (bytes)
Data(0,String,"1","2","3","4").len() //-->8 bytes (ASCIIZ)</langsyntaxhighlight>
 
Put the data into a variable, same results: a:=123; a.len() --> 1
 
There is also a size property which returns the size of the underlying [implementation] data structure.
{{omit from|6502 Assembly|The hardware doesn't know or care about variable size.}}
{{omit from|68000 Assembly}}
{{omit from|8080 Assembly}}
{{omit from|8086 Assembly}}
{{omit from|ARM Assembly}}
{{omit from|AWK}}
{{omit from|Clojure}}
{{omit from|E}}
{{omit from|gnuplot}}
{{omit from|Groovy}}
{{omit from|GUISS|Does not have variables.}}
{{omit from|Java}}
{{omit from|JavaScript}}
{{omit from|LaTeX}}
{{omit from|Logtalk}}
{{omit from|Make}}
{{omit from|Maxima}}
{{omit from|MIPS Assembly}}
{{omit from|NetRexx}}
{{omit from|PlainTeX}}
{{omit from|Processing}}
{{omit from|XSLT}}
{{omit from|X86 Assembly}}
{{omit from|Unlambda|Does not have variables.}}
{{omit from|Z80 Assembly}}
1,150

edits