Does being a constant make a difference?

Referring to the TMRh20 RF24 Class Documentation I notice a small discrepancy.

The function openWritingPipe() is declared this way:
void RF24::openReadingPipe (uint8_t number, const uint8_t * address )

The address instantiation example is:
uint8_t addresses[][6] = {"1Node","2Node"};

I notice the reserved word 'const' is missing in the instantiation.

Does this make any difference? Should the instantiation be:
const uint8_t addresses[][6] = {"1Node","2Node"}; ?

The address of the first element of that array is a constant. The array can't move because it's a named variable. If you wanted the contents of the array to also be constant, then you could put the const keyword there.

The array would be not-constant if it was in a dynamically allocated area, such as a malloc(). But then it wouldn't be named this way.

The 'const' keyword in the function parameter means "I promise not to change the value pointed to by the pointer you pass". If that keyword was NOT there and you tried to pass in a pointer to a 'const uint8_t' you would get an error (or at least a stern warning). When writing functions it is a good idea to put 'const' on pointers you aren't going to write through: It protects you from coding mistakes that write through the pointer and it allows the user to pass a pointer to a constant.

MorganS:
If you wanted the contents of the array to also be constant, then you could put the const keyword there.

May I trouble you for a code example. I don't quite understand what you are saying.

Thanks

johnwasser:
When writing functions it is a good idea to put 'const' on pointers you aren't going to write through: It protects you from coding mistakes that write through the pointer and it allows the user to pass a pointer to a constant.

That seems like a very good idea. :slight_smile: It's always been a problem to me with the 'C' languages that all data seems very, very vulnerable to the inadvertent.

Question, though:
If you have a parameter like address here
void RF24::openReadingPipe (uint8_t number, const uint8_t * address )

do you have to send it something declared as
const uint8_t addresses[][6] = {"1Node","2Node"};

or can you send it a non-constant
uint8_t addresses[][6] = {"1Node","2Node"}; ?

vagulus:
I notice the reserved word 'const' is missing in the instantiation.

Does this make any difference? Should the instantiation be:
const uint8_t addresses[][6] = {"1Node","2Node"}; ?

No. The function promises not to change what it is passed. You don't need to pass a const.

Example:

void foo (const int bar)
  {
  Serial.println (bar);
  }
  
void setup ()
  {
  Serial.begin (115200);
  }
 
void loop ()
  {
  int whatever = 42;
  foo (whatever);
  delay (100);
  }

The function "foo" promises not to change its argument. However the argument does not have to be const.

Thank you Nick