Sizeof()

From Microduino Wiki
Jump to: navigation, search

sizeof() operator

  • Description

Sizeof operator returns the number of the bytes of a variable type, or the bytes the number occupies in array.

  • Syntax
sizeof(variable)

Parameter

  • variable: any variable type or array(such as int,float,byte)
  • Sample code

Sizeof operator is very effective to deal with the arrays, and it can conveniently change the size of the array, without destroying other parts of the program.

This program prints out a string of a text characters at one time. You can try to change the string.

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.write(myStr[i]);
    Serial.println();
  }
  delay(5000); // slow down the program
}

Please pay attention of the total number of bytes sizeof return. Therefor, for the lager variable type, like int, for loop looks like this.

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

[Return to Arduino Syntax Manual]