Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

3.3. Another Example of Assignment

Time for another example. This bit of code demonstrates a few more new things which we'll explain in a minute.

Example 3-3. displaying_variables.c

#include <stdio.h>

int
main()
{
  short first_number = -5;
  long second_number, third_number;

  second_number = 20000 + 10000;

  printf("the value of first_number is %hd\n", first_number);
  printf("the value of second_number is %ld\n", second_number);
  printf("the value of third_number is %ld\n", third_number);

  return 0;
}
    

We've used a short and two long variables. We could have used int variables but chose to use other types to show how similar they are. In the first line of main() we declare a variable and give it a value all in one line. This is pretty normal. The second line declares two variables at once by separating them with a comma. This can be handily but code is often more readable when variable declarations get a line to themselves.

The third line is very like some code from the first example, the addition operator produces the value 30000 which gets stored in second_number. The last thing to point out is that instead of %d, the format string of printf() contains %hd for the short variable and %ld for the long variables. These little groupings of characters are called conversion specifiers. Each type of variable has it's own conversion specifier. If you want to print a single percent sign ("%") you must write %%.

When you compile and run this you will see the value of your variables. The value of third_number will be strange. This is because it was never assigned a value. When you declare a variable, the operating system allocates some memory for it. You have no way of know what this memory was used for previously. Until you give your variable a value, the data stored in it is essentially random. Forgetting to assign a value to a variable is a common mistake among beginning programmers.

 
 
  Published under the terms of the GNU General Public License Design by Interspire