tags:

views:

115

answers:

3

Hi I was wondering what values would argv[1] or argv[2] be, if i failed to provide it with command line arguments

+2  A: 

It would be garbage NULL.

Therefore you should always first test the argc (argument count) before trying to access the command line arguments.

See this for more detailed information.

missingfaktor
This answer is slightly wrong as `argv[1]` wouldn't contain garbage, it would contain `NULL`.
Omnifarious
@Omnifarious : Corrected. Thanks for pointing.
missingfaktor
It would be more correct to say "`argv[argc]` will be `NULL`". `argv[1]` would be `NULL` if `argc` is 1 (which is nearly always the case if no parameters are passed to the program in a 'hosted environment', but not guaranteed). Of course, `argv[2]` (which the OP asked about) would be undefined in that case.
Michael Burr
A: 

a segfault if you are lucky, garbage if you aren't.

The only safe way to use argv, is to treat it as an array of argc elements.

for (int ii = 0; ii < argc; ++ii)
{
    // safe to use argv[ii];
    cout << argv[ii];
}

int ix = somevalue;
if (ix >= 0 && ix < argc)
{
    // safe to use argv[ix];
}

Note to Jerry. A segfault is what you get when you de-reference NULL on most architectures.

John Knoeller
+6  A: 

You've gotten an amazing number of incorrect answers to this. With nothing entered on the command line, argv[0] will still normally contain the name of the program, so argc will be 1. argv[argc] will contain a null pointer (always, on every conforming implementation of C or C++). In the C standard that requirement is at the second bullet of §5.1.2.1.1/2. In the C++ standard it's at §3.6.1/2.

Jerry Coffin
I stand corrected. Thanks for the standard reference.
Michael Myers
This is a nice detail. but the other answers aren't 'incorrect'. if you de-reference argv[1] you will get garbage or a segfault, the fact that the value is supposed to be null is sort of beside the point. It's just as correct to say that arg[1] 'contains' garbage than it is to say that argv[0] 'contains' the program name.
John Knoeller