Tutorial 3 – Arguments

Currently our program outputs some text to the screen. But this text is the same every time you run the program. Obviously most programs do different things depending on what the user inputs to them. So lets have a look at passing data into our application.

We’ll start off with the same code as from Tutorial 2 but we’ll be changing the main function prototype to the following:

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

What we’ve done here is added 2 arguments to the main function. These are just values that are passed into the function and can be used by any code within it. argv is a list of strings that are given to the program on startup. argc is the count of how many strings are contained in argv.

Inside our main function we’re going to use the following:

for(int i = 0; i < argc; i++)
    printf("%s\n", argv[i];

The first thing you see here is called a for loop. This is just a piece of code that will cause any code contained within it’s curly brackets to repeat a given number of times. In this case we’re starting with an index “i” and repeating the printf and incrementing the index each time until the index is the same as the value stored in argc.

The printf function in this case is printing out each item stored in argv as a string of characters.

To run this program we can open up a command prompt, navigate to where the executable is and type the following:

myprogram.exe first second third

What you should then see printed out is the following


What you should notice here is that the program name, along with every other word that you typed, have been passed to the program via the argv variable
There’s a couple of new concepts covered in this tutorial (e.g. The “*” just before argv and the “[]” just after it, as well as the for loop). Don’t worry if you don’t fully get what these mean at the moment. As long as you understand that data can be passed into functions through arguments then you’ve got what you needed from this tutorial! Any other things should hopefully become more concrete as the tutorials carry on.

  1. No comments yet.
  1. No trackbacks yet.

Tell me what you think!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: