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
: The thing to get the size of. Allowed data types: any variable type or array (e.g. int
, float
, byte
).Returns
The number of bytes in a variable or bytes occupied in an array. Data type:
.size_t
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.
1char myStr[] = "this is a test";2
3 void setup() {4 Serial.begin(9600);5 }6
7 void loop() {8 for (byte i = 0; i < sizeof(myStr) - 1; i++) {9 Serial.print(i, DEC);10 Serial.print(" = ");11 Serial.write(myStr[i]);12 Serial.println();13 }14 delay(5000); // slow down the program15 }
Notes and Warnings
Note that
sizeof
returns the total number of bytes. So for arrays of larger variable types such as int
s, the for loop would look something like this.1int myValues[] = {123, 456, 789};2
3 // this for loop works correctly with an array of any type or size4 for (byte i = 0; i < (sizeof(myValues) / sizeof(myValues[0])); i++) {5 // do something with myValues[i]6 }
Note that a properly formatted string ends with the NULL symbol, which has ASCII value 0.
See also
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.