View previous topic :: View next topic |
Author |
Message |
EdWaugh
Joined: 07 Dec 2004 Posts: 127 Location: Southampton, UK
|
Conditional ternary operator ?: |
Posted: Wed Apr 04, 2007 5:12 am |
|
|
Hi everyone,
I'm trying to use this code on v3.245 but I get a 'bad expression syntax' error. Can anyone suggest what I'm doing wrong?
Code: |
fprintf(rda2_strm, "I have %d apple%s\n", apples, (apples == 1) ? "" : "s");
|
cheers
ed |
|
|
kender
Joined: 09 Aug 2004 Posts: 768 Location: Silicon Valley
|
|
Posted: Wed Apr 04, 2007 5:40 am |
|
|
If I understand everything correctly, the expressions left of ? in ?: should be numeric (char, int, float, etc). |
|
|
EdWaugh
Joined: 07 Dec 2004 Posts: 127 Location: Southampton, UK
|
|
Posted: Wed Apr 04, 2007 6:03 am |
|
|
aha, that does seem to compile but I'm sure the way I'm trying to use it is legitimate in C.
I found that this compiles:
Code: |
printf("I have %d apple%s\n", apples, (apples == 1) ? ("") : ('s'));
|
where "s" is traded for 's'. Is it because the first way is using pointers to constant data which v3 doesn't support? |
|
|
EdWaugh
Joined: 07 Dec 2004 Posts: 127 Location: Southampton, UK
|
|
Posted: Wed Apr 04, 2007 6:38 am |
|
|
actually although that code compiles now it just spits out garbage when it gets executed...
Nevermind, maybe I'll just have to do it the long way! |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Wed Apr 04, 2007 11:53 am |
|
|
I think it's because CCS doesn't like the constant strings. If you change
it so the strings are in ram arrays, then it works. Example:
Code: |
#include <16F877.H>
#fuses HS, NOWDT, BROWNOUT, PUT, NOLVP
#use delay(clock=20000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, ERRORS)
//==========================
void main()
{
int8 apples;
int8 no_char[1] = 0;
int8 s_char[2] = "s";
apples = 6;
printf("I have %d apple%s\n", apples, (apples == 1) ? no_char : s_char);
while(1);
} |
|
|
|
Ttelmah Guest
|
|
Posted: Wed Apr 04, 2007 12:36 pm |
|
|
%d, expects to receive a single byte numeric value, not a 'string'. The syntax is not correct C. However on many compilers (where strings are held in RAM), it may result in the value of the first byte in the string being printed (most though will just complain). The single inverted commas, give a character constant, which does have a numeric value. However you need to translate both values into this form.
Best Wishes |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Wed Apr 04, 2007 12:42 pm |
|
|
The %d is getting 'apples' as the variable. |
|
|
|