Nyxynyx
Nyxynyx

Reputation: 63687

Loop does not set value correctly

Why does the loop below not set the pinMode to OUTPUT for the pins in the array pins[]?

int pins[21];

void setup() {

    int pins[] = {13,
              3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
              14, 15, 16, 17, 18, 19, 20, 21, 22, 23};

    for (int i = 0; i < sizeof(pins); i++) {
        pinMode(pins[i], OUTPUT);
    }

}

To get it to work, I have to set them manually:

pinMode(3, OUTPUT);    
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
// ...

Upvotes: 0

Views: 141

Answers (4)

Jerry Coffin
Jerry Coffin

Reputation: 490338

Although you can use sizeof(array)/sizeof(array[0]) or a template to compute the size of the array (or, equivalently, use it to find the end of the array), if you're using a reasonably current compiler, it already knows how to handle the job correctly on its own:

for (auto i : pins)
    pinMode(i, OUTPUT);

At least in my opinion, this seems like the simplest of the three.

Upvotes: 0

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153955

For starters, sizeof(pins) will be sizeof(int) times the number of entries in pins. Accessing values outside the range causes undefined behavior. You probably meant to use

sizeof(pins)/sizeof(pins[0])

or in C++ just size(pins) with a suitable function template like

template <typename T, std::size_t Size>
constexpr std::size_t size(T(&)[Size]) { return Size; }

Why the functions don't work can't be seen from the code snippet you provided as the code doesn't include the definition of the functions (or macros) pinMode().

Upvotes: 0

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58281

Wrong breaking condition causes Undefined behaviour due to n index-out-of bound problem :

for (int i = 0; i < sizeof(pins); i++)
                    ^-----------^ 

should be:

for (int i = 0; i < sizeof(pins)/sizeof(pins[0]); i++)
                    ^---------------------------^

Note: When you apply the sizeof operator to an array type, the result is the total number of bytes in the array.

To understand formula read: Weird behavior when printing array in C?

Upvotes: 2

ouah
ouah

Reputation: 145899

Change sizeof(pins) to sizeof pins / sizeof *pins.

sizeof yields the size of the array in bytes and not the number of elements of the array.

Upvotes: 1

Related Questions