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?

asked Sep 5, 2015 at 4:59

1 Answer 1

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.

answered Sep 5, 2015 at 5:41
5
  • 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. Commented Sep 5, 2015 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). Commented Sep 5, 2015 at 11:30
  • Thanks @JRobert that's a good idea. Is that all I need to define to use it? Commented Sep 5, 2015 at 20:07
  • 1
    You also need to use the countof define like this: for(int a = 0; a < countof(allOutputPins); a++){ Commented Sep 5, 2015 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. Commented Sep 5, 2015 at 22:16

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.