Discussion
What will be the output of this program (prg_3.c)?
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char* argv[])
{
int answer;
answer=atoi(argv[1])+atoi(argv[2]);
printf("%d",answer);
return 0;
}The program is run as:
C:\TC\BIN>prg_3.exe 10 20
Answer: C
Correct answer: 30
Command line arguments always arrive as strings, never as numbers. With the command line prg_3.exe 10 20, argv[1] is the two-character string "10" and argv[2] is "20". Adding those directly would add two pointers, which C does not even permit, so the program converts each with atoi - ASCII to integer, declared in <stdlib.h> - giving \[ 10 + 20 = 30. \] Two habits are worth taking from this. First, atoi reports no errors: given text that is not a number it simply returns 0, which is indistinguishable from a genuine "0", so production code uses strtol instead. Second, the program never checks argc before reading argv[1] and argv[2]; run with fewer arguments it would dereference a null pointer and crash. The command line had been lost from this record and is restored above.
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