0

I am trying to use format specifier within switch however compiler returns error: expression result unused

 const char* text;
 const char* input;
 int i=2;
 input = "orange";

 switch(i){
 case 1:
      text = "%s is color", input;
      break;
 case 2:
      text = "%s is fruit", input;
      break;
 default:
      break;
 }
4
  • 1
    First, you have to allocate memory for strings like: char text[128]; char input[128]; Then, you could use for example sprinf like this: sprintf(text, "%s is color", input); Commented Jul 5, 2018 at 7:50
  • It's actually not completely clear what you're trying to achieve. Please tell us what you intend to do with text. Commented Jul 5, 2018 at 7:55
  • 5
    The format specifier functionality is not a language-level thing, it's simply implemented by the printf() family of functions. In general in C if you want something "complicated" (such as converting various values to string representations) to happen, you need to call a function that implements that. Commented Jul 5, 2018 at 7:55
  • regarding: text = "%s is color", input; and similar statements: This is nonsense. Your compiler is telling you that. Strongly suggest using sprintf() to format the contents of a char array, then you could assign the address of that array to input or text Commented Jul 5, 2018 at 21:51

2 Answers 2

3

You want to use sprintf or snprintf.

char text[128];
const char* input;
int i=2;
input = "orange";

switch(i){
case 1:
    sprintf(text, "%s is color", input);
    break;
case 2:
    sprintf(text, "%s is fruit", input);
    break;
default:
    break;
}
Sign up to request clarification or add additional context in comments.

5 Comments

For this to make sense, text must point at allocated memory and it can't be a const char*.
This it not goint to work, text is not initialized and probably that's not what the OP wants
What about text?
@Lundin Thanks. I spotted it too and was about to fix it.
text is getting initialised within the switch case, and i need to print it outside it switch case
3

You probably want somewhing like this:

 const char* text;
 const char* input;
 int i=2;
 input = "orange";

 switch(i) {
 case 1:
      text = "%s is color";
      break;
 case 2:
      text = "%s is fruit";
      break;
 default:
      break;
 }

 printf(text, input);

2 Comments

You probably want to assign something to text in the default case (or omit default: and just initialize text at the declaration).
this will cause some compilers, like gcc to output a warning message about the security risk of using a variable pointer for the format string, rather than the actual format literal.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.