1

I am constantly receiving:

error: called object is not a function or function pointer

When using ternary operator like that:

puts("\nx: " (0 == 1) ? "y1\n" : "y2\n");


What am I doing wrong?

Morwenn
  • 21,684
  • 12
  • 93
  • 152
Imobilis
  • 1,475
  • 8
  • 29
  • Please, don´t pay attention to the content of the line. I just exemplified it. The point is in the syntax, which remains the same as the origin. – Imobilis Mar 18 '15 at 12:39

4 Answers4

3

You are attempting to call an object which is neither a function nor a function pointer! In particular, the compiler is seeing the open paren after the string and thinks (as much as a compiler can be said to "think") that you are trying to invoke a function call. You cannot concatenate a string with the ternary operator as you are trying to do. Try:

printf("\nx: %s", (0 == 1) ? "y1\n" : "y2\n");
William Pursell
  • 204,365
  • 48
  • 270
  • 300
2
puts("\nx: " (0 == 1) ? "y1\n" : "y2\n");

This is not the right way to do what you want, because you cannot concatenate C strings like this.

You can do this using puts():

puts("\nx: ");
puts((0==1) ? "y1\n" : "y2\n");

EDIT: (Suggested by @WilliamPursell

To avoid the appending of an unwanted newline character, use fputs() instead of puts().

fputs("\nx: ");
fputs((0==1) ? "y1\n" : "y2\n");
shauryachats
  • 9,975
  • 4
  • 35
  • 48
1

You can not concat the strings the way you do.

The simple solution is to use printf

printf("\nx: %s", (0 == 1) ? "y1\n" : "y2\n");

or if you insist on using puts you need the strcat function from string.h

char s[256] = "\nx: ";
puts(strcat(s, (0 == 1) ? "y1\n" : "y2\n"));
halex
  • 16,253
  • 5
  • 58
  • 67
0

This is your code

"\nx: " (0 == 1) ? "y1\n" : "y2\n"
/*     ^ this is ignored        */

so it seems as if the string literal was being called as a function -> "\nx: "(0 == 1), doesn't it look like that?

You can achieve what you want with the printf() function like this

printf("\nx: %s\n", (0 == 1) ? "y1" : "y2");
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97