aboutsummaryrefslogtreecommitdiffstats
path: root/source/arduino/sizeof.rst
blob: a95dfbf177f47cae38b5d50594556034b9a412fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
.. _arduino-sizeof:

sizeof
======

Description
-----------

The sizeof operator returns the number of bytes in a variable type,
or the number of bytes occupied by an array.



Syntax
------

sizeof(variable)



Parameters
----------

variable: any variable type or array (e.g. int, float, byte)



Example code
------------

The sizeof operator is useful for dealing with arrays (such as
strings) where it is convenient to be able to change the size of
the array without breaking other parts of the program.



This program prints out a text string one character at a time. Try
changing the text phrase.



::

    char myStr[] = "this is a test";
    int i;
    
    void setup(){
      Serial.begin(9600);
    }
    
    void loop() { 
      for (i = 0; i < sizeof(myStr) - 1; i++){
        Serial.print(i, DEC);
        Serial.print(" = ");
        Serial.println(myStr[i], BYTE);
      }
    }
    

Note that sizeof returns the total number of bytes. So for larger
variable types such as ints, the for loop would look something like
this.



::

    for (i = 0; i < (sizeof(myInts)/sizeof(int)) - 1; i++) {
      // do something with myInts[i]
    }