0

I want to use an element of an array (in this case element 3) as a loop variable giving it a simple name like "c". (This code is for the Arduino, but should look similar in standard C.) The question is: is there any way to make the compiler accept the c = 5 statement in the for-loop?

byte array[5];
#define c  (int) (byte *) array[3]  

void setup() {
  Serial.begin(9600);
  Serial.println("this only works with a work-around:");
  Serial.print("address of array: ");
  Serial.println( (int) &array );
  Serial.println("this is the loop:");
  for ( /* what you want is: c = 5 */ 
        /* what the compiler requires: */ array[3] = 5; 
        c < 10; c++) Serial.println(c); 
  // the compiler does not accept c = 5
  Serial.println("this works but it wasts time:");
  while (c != 5) c++;
  for ( ; c < 10; c++) Serial.println(c);
}

void loop() {
}
1
  • #define c ((int) array[3]) Commented Jan 12, 2014 at 13:13

3 Answers 3

1
// quod licet int non licet byte
   int array[10]; // byte does not work
// ^^^ that makes the difference

#define c  (int) (byte *) array[3]  
#define d  (int) (byte *) array[4]  

void setup() {
  Serial.begin(9600);
  Serial.println("this is the loop:");
  for (c = 2; c < 5; c++) {     // this loop starts at 2
    for (d = 3; d < 6; d++) {   // this loop starts at 3
      Serial.print(c);
      Serial.print(" ");
      Serial.println(d);
    }
  }
  for (int i = 0; i < 10; i++) Serial.println(array[i]);
}

void loop() {}
Sign up to request clarification or add additional context in comments.

Comments

0

Hi you nedd to use atoi() function:

ascii to integer converter

 c=atoi(array[3]);

hope this help you.

Comments

0

unfortunately, I had to find it out myself. This seems to be the best way to give names to certain array elements and use them in for-loops (target is the Arduino environment).

#define SET(x,y) while (x != y) x++
/* thanks to the cleverness of the compiler this macro does not waste time at run-time */

byte array[10];
#define c  (int) (byte *) array[3]  
#define d  (int) (byte *) array[4]  

void setup() {
  Serial.begin(9600);
  Serial.println("this is the loop:");
  SET(c,2);
  for ( ; c < 5; c++) {     // this loop starts at 2
    SET(d,3);
    for ( ; d < 6; d++) {   // this loop starts at 3
      Serial.print(c);
      Serial.print(" ");
      Serial.println(d);
    }
  }
  for (int i = 0; i < 10; i++) Serial.println(array[i]);
}

void loop() {}

When you print the array contents at the end you see the last values of the loop variables c and d (5 and 6).

Comments

Your Answer

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.