Understanding Pass-by-Value

Hello,

I came across this code to tell you whether a year is a leap year (Beginning C for Arduino, 2nd edition, Jack Purdum).

And I wonder how it is possible that mydata gets altered when readline is using pass-by-value in readline(mydata). I thought pass by value meant that readline make a copy of mydata and uses it in its function. So I don't get how it alters the array that mydata is. Or do I miss something? Is mydata maybe altered another way?

So basically: how does what i type in the serial monitor end up in int year? I just don't see it..

I'm a noobcake i'm sorry! thanks

#define MAXCHARS 10

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0){
    int buffercount;
    int year;
    char mydata[MAXCHARS + 1];

    buffercount = readline(mydata);
    year = atoi(mydata);
    Serial.print("year: ");
    Serial.print(year);
    Serial.print(" is ");
    if (isleapyear(year) == 0){
      Serial.print("not ");
    }
    Serial.println("a leap year");
    }
  }

int isleapyear(int yr){
  if(yr % 4 == 0 && yr % 100 != 0 || yr % 400 == 0){
    return 1;
    }
    else{
      return 0;
  }
}

int readline(char str[]){
  char c;
  int index = 0;
  while (true){
    if(Serial.available() > 0){
    index = Serial.readBytesUntil('\n',str, MAXCHARS);
    str[index] = '\0';
    break;
  }
}
return index;
}

int readline(char* str)Any clearer now?

absoluyely not :o haha

You're passing an array (str) by reference in "readline". Passing by reference is similar to passing by pointer - in that it allows the function to edit "str".

Arrays are always passed by reference, rather than by value...

Rather than passing an array, I much prefer to pass a pointer to the first object in the array i.e. position 0 and also pass the length of the array. I personally don't like passing an array.

andyh-1963:
Rather than passing an array, I much prefer to pass a pointer to the first object in the array i.e. position 0 and also pass the length of the array. I personally don't like passing an array.

The name of the array is a pointer to the first element.