2

I am writing some code for a graphical LCD driven by an ATmega328, using the Arduino build chain with Stino as my IDE. I have a function which formats and displays a number with a label. This is the function:

void displayNumber(float value, char* label)

I realise that both parameters could be consted, but to maintain compatibility with some other code, they are like this.

If I call the function as follows:

displayNumber(externalTemp, "MAX");

It works fine. I understand string literals behave strangely in that they can't be modified (undefined behaviour) but they are not declared as const char* but char*.

If I try using the ternary operator to pass an argument to the function:

displayNumber(externalTemp, animate10s?"MAX":"MIN");

I get a compiler error:

invalid conversion from 'const char*' to 'char*'

Why is the ternary operator consting my string?

The compiler specifically used is avr-gcc/avr-g++ version 4.3.2, the one bundled with Arduino Beta 1.5.6-r2.

Cybergibbons
  • 464
  • 3
  • 9

1 Answers1

4

There is (or was until recently) a deprecated conversion from string literal to char * (without the const it would normally have), which is what lets the simple call work.

The ternary expression is not a string literal, so the conversion cannot be applied to it.

(Your best solution would be to make sure the function parameter is properly declared as taking const char *.)

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
  • Thanks. Is there a way to force a string literal be dealt with as const so that strong type checking can be used? – Cybergibbons Mar 10 '14 at 10:14
  • 1
    @Cybergibbons You can try to make the `deprecated-writable-strings` warning into an error with `-Werror=deprecated-writable-strings`. – juanchopanza Mar 10 '14 at 10:23