2
#include <iostream>

using namespace std;

int main(int argc, char* argv[]) {

    int i;

    i = 1;
    while (i < argc) {
        cout << argv[i] << endl;
        i = i + 1;
    }

}

Command line arguments are listed as b f i

I'm just learning about argc and argv, but from what I understand, argc is the number of arguments passed from the command line (3 in this case), and argv is the array of these arguments, [b f i] in this case. So using that, I intuitively think that this loop should output argv[1], then argv[2], then terminate. The final output would therefore be:

f

i

However, the solution given is:

b

f

i

Which is baffling to me. Would anyone be able to explain where I'm going wrong with my thought process?

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
Mock
  • 359
  • 1
  • 3
  • 11

1 Answers1

5

argv[0] is actually the name you used to run the program.

So if you ran:

./myProgram b f i

argv contains ["./myProgram", "b", "f", "i"], and argc == 4.

(This isn't actually part of The Standard, but is the normal behaviour on most platforms).

As a mildly interesting aside, note it is guaranteed that argv[argc]==nullptr, so you could iterate over the valid pointers, rather than using an index, if you wanted to.

A for loop keeps the iteration logic more self-contained than a while; the more common form of the loop you have written would be like this:

for (int i = 0; i < argc; ++i) {
    std::cout << argv[i] << '\n'; // see note below
}

Also, please reconsider your use of what are often considered bad practices: using namespace std; and endl.

Community
  • 1
  • 1
BoBTFish
  • 19,167
  • 3
  • 49
  • 76
  • 1
    Ohhh, I see, so this is argv is actually an array with 4 elements. That clears this question right up and also makes the remainder of my argc/argv practice intuitive, thank you very much! – Mock Feb 03 '17 at 08:22
  • @Mock Please also see the extra note I just added on some other style issues. – BoBTFish Feb 03 '17 at 08:55
  • Is `endl` bad practice because it doesn't use the namespace, or is there some other reason ? – user1952500 Feb 03 '17 at 09:27
  • @user1952500 Read the link: it is confusing because it does 2 unrelated things, and people often misunderstand that. – BoBTFish Feb 03 '17 at 09:30