Discussion
What will be the output of the program ?
#include <stdio.h>
#include <string.h>
int main()
{
char str1[5], str2[5];
int i;
gets(str1);
gets(str2);
i = strcmp(str1, str2);
printf("%d\n", i);
return 0;
}
Answer: A
Correct answer: Unpredictable integer value
Two things make the result unpredictable. The buffers are only five bytes and gets() cannot limit what it reads, so any input of five characters or more overruns them. And even with short input, strcmp returns a value whose sign is defined but whose magnitude is not - some libraries return the difference of the first differing characters, others just -1, 0 or 1. Code should test the sign, never a specific number.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development