Zerobu
Zerobu

Reputation: 2701

Values of Argv when something is not entered from command line

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

Upvotes: 2

Views: 803

Answers (3)

John Knoeller
John Knoeller

Reputation: 34198

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.

Upvotes: -1

missingfaktor
missingfaktor

Reputation: 92106

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.

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490623

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.

Upvotes: 8

Related Questions