[Masters of the Void]
3. Variables and User Input

Previous | Next

Now that you have learned how to write "Masters of the void" onto the screen, and you have probably already tried writing something else between the quotes or duplicating the printf-line, we would like to get more daring. To do this, C has variables. A variable is simply a name into which you can put a value of a specific data type. We already know int, so let's create a variable with this data type. Change your main.c file so main() looks like the following:

int	main()
{
	int		myNumber;
	
	myNumber = 7;
	printf( "I am %d years old.", myNumber );

	return 0;
}

The first line defines a variable named myNumber which may hold data of type int. Defining something basically means you tell your compiler what a certain word is supposed to mean. In this case, you tell the compiler that you want some memory in which you can keep any number, and that whenever you refer to myNumber, you want the compiler to insert whatever you stored in myNumber before. The second line now assigns the number 7 to this variable. This is done using the = operator, which writes whatever is to its right into the container to its left. Note that, even though main() and myNumber both have the data type int, main() is not a variable and myNumber is not a function. A function is a list of commands, while a variable is a place to store data.

But what does the printf-line do? Well, printf() doesn't really print the text to the screen just like that, rather, it looks at the text you give it and looks for placeholders. Placeholders always start with a per cent sign ("%") and then have one character after them that indicates what should be inserted here. In our case, that character is "d", which means "decimal number", which means it wants an int. You can also use "%s" to mean "string of characters", i.e. a bit of text. It will replace every such placeholder with a value and then print that to your screen.

So, where does it get the values from? Well, you specify them as additional parameters after your text with placeholders. So if you wanted to provide a number and a name, you could write:

printf( "I am %s and I'm %d years old", "Pete", 29 );
Obviously, this would be a little pointless, as you could just write "I am Pete and I'm 29 years old" right away, but when you're using variables this can come in really handy to output whole sentences assembled from data the user entered: If you run the original program (open the console window and do a Build and Run), it writes "I am 7 years old." to the console. So, you see that myNumber is automatically replaced by its value. Neat, huh? Now let's try another neat thing:
int	main()
{
	int	a,
		b,
		c;
	
	a = b = c = 23;
	printf( "a = %d, b = %d, c = %d", a, b, c );
	return 0;
}

Note how, in this example, there are three equals signs chained together. Run it, and you will get "a = 23, b = 23, c = 23" on your screen. This comes from the fact that these statements are executed from right to left. That is, first 23 is put into c, then c (which contains 23 now) is put into b and then b (which now also contains 23) into a.

Another thing that may catch your eye here is how I defined a, b and c. You can define multiple variables by writing the data type once and then specifying a list of variable names separated by commas. Again, where you insert spaces, newlines and tabs is mandatory, their count isn't. Most programmers put each variable on its own line, but since C couldn't care less about how much whitespace you put between identifiers, you could also write:

int	a, b, c;

Just remember to finish off the definition of a variable with a semicolon (";"). Also, most versions of C require variable definitions to go at the top of a "{ ... }" block, you can't just put them anywhere you want.

But now, wouldn't you want to do something more dynamic than just outputting the same text? OK. Let's get started with input from the user. With all you already know, it'll be pretty easy. Change your version of main() again:

int	main()
{
	int		userInput;
	
	printf( "Please enter your age: " );
	
	scanf( "%d", &userInput );
        fpurge( stdin );
	
	printf( "You are %d years old.\n", userInput );
	
	return 0;
}

First we define an integer variable named userInput. This is the place the data the user entered will go. Then we output some text that tells the user he/she is to enter a number. And now comes the actual part that gets the user input. scanf() is the opposite of printf(), and reads stuff from the keyboard. Just that in this case the placeholders tell scanf() what kind of data to read, and the parameters you pass it are the destination where you want the read data to go. Also note the "&" before the userInput variable. We'll learn why this is necessary later when we do our own parameters. For now, just see it as a quirk that scanf() requires before all its destination parameters.

The call to fpurge() makes sure any excess characters entered after the number are discarded, and also tells the system you are finished reading text and will be writing again. stdin is the name of the input stream used by scanf(). Think of it as the name C gives to your keyboard. There's also stdout used by printf() and stderr used to log errors. But you won't need those anytime soon.

Finally, to prove that the value arrived properly, we write the variable's value to the screen again. Here you might note some gibberish at the end of the scanf text and the actual text we want to printf: \n. Whenever you encounter a backslash inside some text enclosed in quotes, this means that you want to express some special character inside your text. What character is to be inserted is specified by the next character after the \.

In this case it is an n, which means "newline", that is, we tell the compiler to start a new line, just as if we hit the return key on the keyboard. You can also use \t to type a tab, \" to type a quote, and to type a backslash, you use \\ so it knows you really want a backslash and this isn't the start of another special character.

Previous | Next

Reader Comments: (RSS Feed)
No comments yet
Comment on this article:
Name:
E-Mail: (not shown on site)
Web Site URL: (optional)
Comment: (plain text only)
Please Enter the following word:
Or E-Mail Uli privately.