You have popped with many questions at the same time. Lets start with the simplest one.
What's the relation between return value of a function and command line arguments?
You don't return 1 because you have 1 command line argument. The return value of any function(including main()) is almost independent of the arguments passed (unless you do something like this inside your code).
#include <iostream>
using namespace std;
int main(int argc, string argv[])
{
//do something here
return argc;
}
Although there's no reason why one shall do it. I gave it to just explain you when return values could depend upon number of arguments(argc
here). In general, they don't depend, return anything you wish from a function(See below).
So should I return arbitrary values from main() ?
I take my words back now. No, you should not return any arbitrary value from main(). Read workmad3's answer. The return value tells the system how the program exited. In our case(pset2, caesar), we return the value 1 when we don't get enough/expected number of command line arguments because we can't process the data further(as it's insufficient). The cs50 graders are designed to detect the value 1 if and only if anything except 2 arguments were passed. Then the grader responds positively. The same case would have been with the value 2 or 3 if graders were designed so(and of course we were also told about that to return 2 or 3 or something else when certain conditions are not met).
What's the case with your code?
In your code, you write int key = atoi(argv[1])
before testing whether really there are 2 arguments passed to main(). If there were actually 2 or more arguments, then it was fine, but what when there was only 1 argument? In that case argv[1]
is empty and you are trying to access its value. As a result it gives Segmentation Fault, which is generally encountered when you try to access a memory location with nothing in it(say NULL).
This is the answer to the question before it was edited.