Question regarding passing a char array to a function

I am writing a program that uses char arrays to serial read / manipulate / write some text. It seems a char array is considered the best approach.

The reading part is in one function and the writing part is in the main loop.
I'm trying to write the code correctly, not just stumble around until it works.

So my confusion has to do with scope of the char array.

Reading this from Tutorialpoint

The value of the name of the array is the address in the computer’s memory of the first element of the array. Since the starting address of the array is passed, the called function knows precisely where the array is stored in the memory. Therefore, when the called function modifies array elements in its function body, it is modifying the actual elements of the array in their original memory locations.

So its not clear how the above approach of passing the array to the function is much different than a global char array

Is it perhaps the small size of Arduino memory makes the distinction of global vs local variables not as important as larger systems?

Thanks
John

So its not clear how the above approach of passing the array to the function is much different than a global char array

A global char array is accessible from all part of the program with no control. A locally declared char array has scope in the function where it is declared and that function explicitly passes the pointer to the array and 'allows' the called code to change the characters.

The distinction may be moot if you are programming on your own and you only have a single threaded program. However, if you return to this in a few months/years (usually details are hazy by then) and see a global array, you may be making unintended changes to the data that other parts of your code do not expect.

I would always encourage variables with the minimum scope that will allow the job to be done. In some cases this will be a global scope, but mostly it does not have to be.

Thank you :slight_smile: Your reply was very helpful, it helped me think deeper into the structure and I think I learned more on how to limit scope in arduino IDE.

John

Marco_c's comments are spot-on. One of the big wins for Object Oriented Programming is the concept of Encapsulation. As he pointed out, if you make data global, every statement in the project file has direct access to that data. If you define the array within a function, only the statements in that function have direct access to the data. I like to think of global data as a prostitute standing at the top of your program and you just gave every statement in your program a $100 bill. If there's a bug with a global array, you have no idea which statement is the father of that bug. If you encapsulate the array within a function, at least you know which house (function) to visit to find the father of the bug.