0

I notice problems with my output pins when I use this method of setting their pinMode:

int allOutputPins[] = {3, 4, 9, 10, 5, A3, 11, 12, 7, 8, A1, A2};


for(int a = 0; a < sizeof(allOutputPins); a++){
   pinMode(allOutputPins[a], OUTPUT); 
  }//end for

Am I doing something wrong?

2

Re “Am I doing something wrong?”, yes :)

The sizeof(allOutputPins) expression returns the size of allOutputPins[] in terms of bytes, so is 24 because the array contains 12 two-byte integers. The loop's last 12 pinMode() calls will be garbage.

Among other ways of fixing the problem, you could change the expression to sizeof(allOutputPins)/sizeof(int) [which has the same value, 12, as (sizeof allOutputPins)/sizeof(int); eg see the syntax entries for the sizeof operator at cppreference.com] or you could change the base type of the array to byte or uint8_t.

| improve this answer | |
  • 2
    I would recommend using sizeof allOutputPins / sizeof allOutputPins[0] instead. This idiom is more robust because it works independently of the type of the array. I would use it even if I change allOutputPins base type to uint8_t. – Edgar Bonet Sep 5 '15 at 6:07
  • 1
    What you needed and were expecting was the count of the items in the array. I need this so regularly, I keep a countof macro, #define countof(a) (sizeof(a)/sizeof(a[0])) in my local.h file (personal file of common idioms). – JRobert Sep 5 '15 at 11:30
  • Thanks @JRobert that's a good idea. Is that all I need to define to use it? – Michael Rader Sep 5 '15 at 20:07
  • 1
    You also need to use the countof define like this: for(int a = 0; a < countof(allOutputPins); a++){ – Nick Gammon Sep 5 '15 at 21:28
  • 1
    You would need to #include <local.h> in your sketch (the Arduino IDE won't know to do it for you); thereafter you can use it anywhere in your sketch, such as how @NickGammon just described. – JRobert Sep 5 '15 at 22:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.