C question based on switch | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

C question based on switch

Why is the output of the code below "abc" ? Does the switch take the case before default always, if a variable is not specifed? switch(printf("ab")){ case 1:printf("b"); break; case 2: printf("c); break; default:printf("z"); }

7th Feb 2019, 12:11 PM
Ajeya Bhat
Ajeya Bhat - avatar
7 Answers
+ 6
Actually the 2 characters printed are 'a' and 'b'. Result of printf is 2 (number of characters output) and inside the switch a 'c' is also printed.
7th Feb 2019, 12:34 PM
Sonic
Sonic - avatar
+ 6
\0 is not printed.
7th Feb 2019, 12:46 PM
Sonic
Sonic - avatar
+ 3
because "a" contains two characters, 'a' and '\0', and printf returns the number of bytes printed, so it executes case 2.
7th Feb 2019, 12:15 PM
Bebida Roja
Bebida Roja - avatar
+ 2
Yes, but Bebida told it as a and \0, as I had previously missed a 'b' in the code😅
7th Feb 2019, 12:37 PM
Ajeya Bhat
Ajeya Bhat - avatar
+ 2
the output is automatically abc because of the above reason
8th Feb 2019, 11:40 AM
Oviya arumugam
Oviya arumugam - avatar
+ 1
printf("ab") is equal to 2 so that the value c is displayed
8th Feb 2019, 11:39 AM
Oviya arumugam
Oviya arumugam - avatar
0
It is correct
8th Feb 2019, 11:52 AM
Oviya arumugam
Oviya arumugam - avatar