Why is the tenary code not working here? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why is the tenary code not working here?

#include <stdio.h> int x=35; int isAdult= if(x<18) ? "Too Young":"Too Old" int main(void){ printf("%u\n", isAdult); return 0; }

8th Feb 2021, 3:40 PM
Jackson Kairani Maina
Jackson Kairani Maina - avatar
10 Answers
+ 2
[Anonymous]95 assigning string in c is a little tricky: you should copy the string to its new emplacement with the help of <string.h> function (such as the strcpy()): https://code.sololearn.com/czvpP186n2JD/?ref=app
9th Feb 2021, 2:30 PM
visph
visph - avatar
+ 4
[Anonymous]95 because ternary operator doesn't expect the 'if' keyword... and your variable doesn't have the correct type to receive string ^^ char var[15] = cond ? "true" : "false";
8th Feb 2021, 3:44 PM
visph
visph - avatar
+ 3
[Anonymous]95 I didn't get any error. I think you did some mistake. See here https://code.sololearn.com/c4lFYNp1axNS/?ref=app
9th Feb 2021, 2:52 PM
A͢J
A͢J - avatar
+ 2
I Am AJ ! Thanks so much
9th Feb 2021, 5:51 PM
Jackson Kairani Maina
Jackson Kairani Maina - avatar
+ 1
D_Stark still not working 👇👇👇 char AGE=35; AGE<18 ? "Too Young":"Too Old"; printf("%s\n", AGE);
8th Feb 2021, 6:53 PM
Jackson Kairani Maina
Jackson Kairani Maina - avatar
+ 1
[Anonymous]95 Your getting muddled up with your types I dont really know c syntax so I guess it will look somthing like this. int age =35; char *x = age<18?"to young":"to Old"; printf("%s\n",x);
8th Feb 2021, 7:52 PM
D_Stark
D_Stark - avatar
+ 1
D_Stark I'm getting this error 👇👇 source_file.c:3:11: error: initializer element is not constant char *x = age<18?"to young":"to Old"; ^~~ source_file.c:5:8: error: expected declaration specifiers or ‘...’ before string constant printf("%s\n",x); ^~~~~~ source_file.c:5:15: error: expected declaration specifiers or ‘...’ before ‘x’ printf("%s\n",x); ^
9th Feb 2021, 10:01 AM
Jackson Kairani Maina
Jackson Kairani Maina - avatar
+ 1
I Am AJ ! This is the error after running the code 👇👇👇 source_file.c:3:15: error: initializer element is not constant char* adult = (x < 18 ? "Too Young" : "Too Old"); ^ source_file.c:4:9: error: expected declaration specifiers or ‘...’ before string constant printf ("%s", adult); ^~~~ source_file.c:4:15: error: expected declaration specifiers or ‘...’ before ‘adult’ printf ("%s", adult); ^~~~~
9th Feb 2021, 10:04 AM
Jackson Kairani Maina
Jackson Kairani Maina - avatar
+ 1
visph thanks so much...again you've helped
9th Feb 2021, 5:51 PM
Jackson Kairani Maina
Jackson Kairani Maina - avatar
0
[Anonymous]95 In ternary operator no need to write if because it's a short cut of if else statement. Here should be int x = 35; char* adult = (x < 18 ? "Too Young" : "Too Old"); printf ("%s", adult);
8th Feb 2021, 7:56 PM
A͢J
A͢J - avatar