Set value variables for loop

I'll try to explain it as simply as I can. I am in the first stages of programming, hence me asking this. The situation is that I have a forloop in which an analog pin is being read, and I want to assign that value to increasing variables. So for (int x = 0 ; x < 7 ; x++), and then assign the read value to Variable[ x ]. What is the most effective to do that? All I can think of is if(x=0){Variable0=value}; and continue the whole list but that'll clutter up the code and potentially slow it down. Help would be appreciated!

Hi Tom_duino,

First step would be using an array for this. See reference for details.

Pay extra attention for indexing:

It also means that in an array with ten elements, index nine is the last element. Hence:

int myArray[10]={9, 3, 2, 4, 3, 2, 7, 8, 9, 11};
// myArray[9]    contains 11
// myArray[10]   is invalid and contains random information (other memory address)

For this reason you should be careful in accessing arrays. Accessing past the end of an array (using an index number greater than your declared array size - 1) is reading from memory that is in use for other purposes. Reading from these locations is probably not going to do much except yield invalid data. Writing to random memory locations is definitely a bad idea and can often lead to unhappy results such as crashes or program malfunction. This can also be a difficult bug to track down.

if(x=0){Variable0=value};
If you don't like suprises, also note the difference between Assignment operator (=) and Equal to comparison operator (==).

1 Like

I did use an array, int Variable[7] = {1,2,3,4,5,6,7}; but my assumption was that saying Variable[ x ] = value; would work, but it doesn't. And about the = and ==, typo, I drafted the code and did it the right way there.

Okay.

I can only show you a loop which should work, as you didn't post the code.

int variable[7] = {1,2,3,4,5,6,7}; 
for (int x = 0; x < 7; x++)
{
  variable[x] = analogRead(A0);
}

1 Like

For fucks sake.... I accidentally made the variable[7] a const int, and not an int.... Goodmorning :confused:

But the compiler was kind enough and warned you about that, right?

haha, thanks I needed that. I've been doing stupid shit all night.

since you say your new I'll mention, there are many array libraries with various tools. most of which keep to from doing anything stupid (though not the const thing :wink: )

perhaps I am bening pedantic, but x can & should be a uint8_t -- 8 bits, unsigned. Just good form.

1 Like

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