Array is empty after one loop for now reason

Hello there,

For some reason the my array (codeList) is cleared after searching in the main loop

int codeList[] = {10,15,20,25,30};
int item = 10;
void setup() {
  for (int i; i < (sizeof(codeList)) / sizeof(int); i++){Serial.println(codeList[i]);}
void loop() {
  // show all items in array
  for (int i; i < (sizeof(codeList)) / sizeof(int); i++){Serial.println(codeList[i]);}

  // search  item in array
  bool succes = false;
  for (int i; i < (sizeof(codeList)) / sizeof(int); i++){
    // if item is in list
    if (item == codeList[i]){
      succes = true;
  //print succes ore not
  Serial.print("succes: ");
  if (succes){Serial.println("True");}

  // delay to make promt readble 

as you will see in the image, in the setup and the first loop it works. but after that he just forgot the array, even if i use const int codeList.

i have no idea why he would do this. so if somane could help i would be greatfull.

Thanks in advance
Maxim D

shouldn't i be initialized to 0? (it's not initialized to anything)

No, the array is ok. The search is failing because of the error that @gcjr found. The loop variable i will not automatically default to zero, except by luck. It will begin at some unknown value, which will probably be greater than the size of the array, so the for-loop will not run even once. I worked the first time because of luck, perhaps some previously unused memory was used which contained zero.

1 Like

Set your compiler warnings to "All" in preferences. you would have gotten these handy warnings:

sketch_jul27a.ino:8:12: warning: 'i' is used uninitialized in this function [-Wuninitialized]
   for (int i; i < (sizeof(codeList)) / sizeof(int); i++)
sketch_jul27a.ino:17:12: warning: 'i' is used uninitialized in this function [-Wuninitialized]
   for (int i; i < (sizeof(codeList)) / sizeof(int); i++)
sketch_jul27a.ino:24:12: warning: 'i' is used uninitialized in this function [-Wuninitialized]
   for (int i; i < (sizeof(codeList)) / sizeof(int); i++)

You would have also gotten some warnings about comparing a signed value (int i) with an unsigned value (sizeof). Those are not a problem in your case but to get rid of the warnings, change "int i" to "size_t i". The type 'size_t' is the type that the 'sizeof' operator returns. Probably 'unsigned int'.

A handy little improvement to your code. Change

sizeof(codeList) / sizeof(int)


sizeof(codeList) / sizeof(codeList[0])

That way, if you change the type of codeList (like to a long or byte or ????) your code will continue to work, unchanged.

You can break; the loop when the item is found so it doesn't check others items for nothing

You could do this way too : xntsRG - Online C++ Compiler & Debugging Tool -

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.