+ 1

Why does the first main function need "%s" in order to print out the text and second one does not?

#include <stdio.h> int main() { int score = 89; if (score >= 90) printf("%s", "Top 10% \n"); else if (score >= 80) printf("%s", "Top 20% \n"); else if (score > 75) printf("%s", "You passed.\n"); else printf("%s", "You did not pass.\n"); } #include <stdio.h> int main() { int num = 41; num += 1; if (num == 42) { printf("You won!"); } }

25th Feb 2020, 4:47 PM
Woody Lin
Woody Lin - avatar
3 Answers
+ 4
Actually, there is a difference. The first parameter is parsed by printf, where it looks for format specifiers. What if that first string contains a substring like %s, %d or any other format? Bad things, that's what. When it hits something like %s, it expects that there is another parameter passed to it, so it will read the second parameter, even if you didn't pass anything. Consider this string: char s[] = "Hello %s"; If we print it with: printf( "%s", s ); we get the expected: "Hello %s" But what if we did this instead? printf( s ); In my case it prints "Hello -m7" Sometimes: "Hello " or "Hello (NULL)" This is undefined behaviour. So, never pass your string as the first parameter, unless it's purpose is to specify the format for the other parameters. Never, ever pass a string as the first parameter that can be modified by the user. ( The user may enter a string that can be used to read out data from the stack which can be used in a malicious way )
25th Feb 2020, 5:27 PM
Dennis
Dennis - avatar
0
You can use both print function in main. There is no any exceptional case. These are two ways to print String value in C You can see here https://www.sololearn.com/learn/C/2914/
25th Feb 2020, 4:54 PM
A͢J
A͢J - avatar