general programming question

For my Arduino Mega (which has multiple serial ports), I'm writing some code which is the same for the different ports. So a part of that code could be: Serial2.available() Serial3.available() But this way, I have to write everything twice!

-> Is there a way to replace the numers 2 & 3 by a variable? So that it becomes something like Serial+number.available()?

(in flash actionscript you could do: ["serial"+number].available() )

void setup(){
  doSomethingWithSerial( &Serial );
  doSomethingWithSerial( &Serial1 );
  doSomethingWithSerial( &Serial2 );
}
void doSomethingWithSerial( Print* printer){
  printer->println("do something with all serial ports");
}

Hope this helps.

If you want more explanation, just ask.

I'm quite new to this, but I think it's not exactly what I need. for example, now I have:

if(Serial3.available() > 0) { 
      buffer = Serial3.read();  
//and more code
}

and

if(Serial2.available() > 0) { 
      buffer = Serial2.read();  
//and more code
}

So at one moment, I might want to run the code for Serial 2. But at another moment, I want to run it for Serial 3. I think your example runs the code for both Serials at the same time right? :)

pap, why not post some psuedo code of what you would like to do.

If you want to use an index variable you could create an array of Serial ports:

HardwareSerial port[] = {Serial, Serial1, Serial2, Serial3};

void setup()                    // run once, when the sketch starts
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
  for(int i=0; i < 3; i++)
     port[i].begin(9600);
}

void loop()                     // run over and over again
{
  port[0].print("sizeof port ");
  port[0].println(sizeof(port));
  port[1].println("hello");
}

The array holds the entire structure so this uses 18 bytes per port. You could use an array of pointers that is similar to what AlphaBeta posted except it uses an index instead of the Serial pointer directly

HardwareSerial* port[] = {&Serial, &Serial1, &Serial2, &Serial3};


void setup()                    // run once, when the sketch starts
{
  pinMode(ledPin, OUTPUT);      // sets the digital pin as output
  for(int i=0; i < 1; i++)
     port[i]->begin(9600);
}

void loop()                     // run over and over again
{
  port[0]->print("sizeof port ");
  port[0]->println(sizeof(port));
}