Code Examples
  Home arrow Code Examples arrow Page 6 - First Steps in Programming
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Actuate Whitepapers 
Moblin 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
CODE EXAMPLES

First Steps in Programming
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 58
    2005-03-23

    Table of Contents:
  • First Steps in Programming
  • Variables That Store Numbers
  • Naming Variables
  • Basic Arithmetic Operations
  • Try It Out: Division and the Modulus Operator
  • Variables and Memory
  • Division Using Floating-Point Values
  • Defining Constants
  • Type Casting in Arithmetic Expressions
  • Try It Out: Arithmetic with Values of Type char
  • Try It Out: Finding the Limits
  • Designing a Program
  • Summary

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    First Steps in Programming - Variables and Memory


    (Page 6 of 13 )

    So far you’ve only looked at integer variables without considering how much space they take up in memory. Each time you declare a variable, the computer allocates a space in memory big enough to store that particular type of variable. Every variable of a particular type will always occupy the same amount of memory—the same number of bytes—but different types of variables require different amounts of memory to be allocated.


    NOTE The amount of memory occupied by variables of a given type will always be the same on a particular machine. However, in some instances a variable of a given type on one computer may occupy more memory than it does on another.

    You saw at the beginning of this chapter how your computer’s memory is organized into bytes. Each variable will occupy some number of bytes in memory, so how many bytes are needed to store an integer? Well, 1 byte can store an integer value from –128 to +127. This would be enough for the integer values that you’ve seen so far, but what if you wanted to store a count of the average number of stitches in a pair of knee-length socks? One byte wouldn’t be anywhere near enough. Consequently, not only do you have variables of different types in C that store different types of numbers, one of which happens to be integers, but you also have several varieties of integer variables to provide for different ranges of integers to be stored.

    As I describe each type of variable in the following sections, I’ll include a table containing the range of values that can be stored and the memory the variable will occupy. I’ll summarize all these in a complete table of all the variable types at the end of this chapter.

    Integer Variable Types

    You have three basic flavors of integer variables that you can declare. Each type is specified by a different keyword, as shown in Table 2-3.

    Table 2-3. Keywords for Integer Variable Types

    KeywordNumber of BytesRange of Values
    int2 or 4 (depending on–32,768 to +32,767 or –2,147,438,648 to
    your computer)+2,147,438,647
    short2–32,768 to +32,767
    long4–2,147,438,648 to +2,147,438,647


    The types short and long are really abbreviations for types short int and long int, but they’re almost always written in their abbreviated forms. Table 2-3 reflects the typical size of each type of integer variable, although the amount of memory occupied by variables of these types depends on the particular compiler you’re using. The only specific requirement is that type long won’t occupy less memory than type int, and type int won’t occupy less memory than type short. Outside of that, the compiler-writer has complete freedom to make the best use of the hardware arithmetic capabilities of the machine on which the compiler is executing.

    Variables of type int should have the size most suited to the computer on which the code is executing. For example, consider the following statement:

    int cookies = 0;

    This statement declares a variable that will occupy 2 bytes on some machines and 4 bytes on others. You may also find that two different compilers on the same machine implement type int with different sizes. This variation may seem a little strange, but the int type is intended to correspond to the size of integer that the computer has been designed to deal with most efficiently, and this can vary not only between different types of machine, but also with the same machine architecture as the chip technology evolves over time. Ultimately, it’s the compiler that determines what you get. Although at one time many C compilers for the PC created int variables as 2 bytes, with more recent C compilers on a PC, variables of type int occupy 4 bytes. This is because all modern processors move data around at least 4 bytes at a time. If your compiler is of an older vintage, it may still use 2 bytes for type int, even though 4 bytes would now be better on the hardware you’re using.


    NOTE The sizes of all these types are compiler dependent. The ANSI standard for the C language requires only that the size of short variables should be less than or equal to the size of type int, which in turn should be less than or equal to the size of type long.

    If you use type short, you’ll probably get 2-byte variables. The previous declaration could have been written as follows:

    short cookies = 0;

    Because the keyword short is actually an abbreviation for short int, you could write this as follows:

    short int cookies = 0;

    This is exactly the same as the previous statement. When you write just short in a variable declaration, the int is implied. Most people prefer to use this form—it’s perfectly clear and it saves a bit of typing.


    NOTE Even though type short and type int may occupy the same amount of memory on some machines, they’re still different types.

    If you need integers with a bigger range—to store the average number of hamburgers sold in one day, for instance—you can use the keyword long:

    long Big_Number;

    Type long defines an integer variable with a length of 4 bytes, which provides for a range of values from –2,147,438,648 to +2,147,438,647. As noted earlier, you can write long int if you wish instead of long, because it amounts to the same thing.

    Integer Constants

    Because you can have different kinds of integer variables, you might expect to have different kinds of integer constants, and you do. If you just write an integer value 100, for example, this will be of type int. If you want to make sure it is type long, you must append an upper- or lowercase letter L to the numeric value. So the integer 100 as a long value is written 100L. Although it’s perfectly legal, a lowercase letter l is best avoided because it’s easily confused with the digit 1.

    To declare and initialize the variable Big_Number, you could write this:

    long Big_Number = 1287600L;

    An integer value will also be type long if it’s outside the range of type int. Thus, if your compiler implementation uses 2 bytes to store type int values, the values 1000000 and 33000 will be of type long by default, because they won’t fit into 2 bytes.

    You write negative integer constants with a minus sign, for example:

    int decrease = -4;
    long below_sea_level = -100000L;

    You can also write integer values in hexadecimal form—that is, to base 16. The digits in a hexadecimal number are the equivalent of decimal values 0 to 15, and they’re represented by 0 through 9 and A through F (or a through f). Because there needs to be a way to distinguish between 9910and 9916, hexadecimal numbers are written with the prefix 0x or 0X. You would therefore write 9916in your program as 0x99 or as 0X99.

    Hexadecimal constants are most often used to specify bit patterns because each hexadecimal digit corresponds to 4 binary bits. The bitwise operators that you’ll see in the next chapter are usually used with hexadecimal constants that define masks. If you’re unfamiliar with hexadecimal numbers, you can find a detailed discussion of them in Appendix A.

    Floating-Point Values

    Floating-point variables are used to store floating-point numbers. Floating-point numbers hold values that are written with a decimal point, so you can represent fractional as well as integral values. The following are examples of floating-point values:

      1.6
      0.00008
      7655.899

    Because of the way floating-point numbers are represented, they hold only a fixed number of decimal digits; however, they can represent a very wide range of values— much wider than integer types. Floating-point numbers are often expressed as a decimal value multiplied by some power of 10. For example, each of the previous examples of floating-point numbers could be expressed as shown in Table 2-4.

    Table 2-4. Expressing Floating-Point Numbers

    ValueWith an ExponentCan Also Be Written in C As
    1.60.16✕1010.16E1
    0.000080.8✕10-40.8E4
    7655.8990.7655899✕1040.7655899E4


    The center column shows how the numbers in the left column could be represented with an exponent. This isn’t how you write them in C; it’s just an alternative way of representing the same value designed to link to the right column. The right column shows how the representation in the center column would be expressed in C. The E in each of the numbers is for exponent, and you could equally well use a lowercase e. Of course, you can write each of these numbers in your program without an exponent, just as they appear in the left column, but for very large or very small numbers, the exponent form is useful. I’m sure you’d rather write 0.5E-15 than 0.0000000000000005, wouldn’t you?

    Floating-Point Variables

    There are three different types of floating-point variables, as shown in Table 2-5.

    Table 2-5. Floating-Point Variable Types

    Number
    Keywordof BytesRange of Values
    float4±3.4E38 (7 decimal digits precision)
    double8±1.7E308 (15 decimal digits precision)
    long double10±1.2E4932 (19 decimal digits precision)


    These are typical values for the number of bytes occupied and the ranges of values that are supported. Like the integer types, the memory occupied and the range of values are dependent on the machine and the compiler. The type long double is sometimes exactly the same as type double with some compilers. Note that the number of decimal digits of precision is only an approximation because floating-point values will be stored internally in binary form.

    A floating-point variable is declared in a similar way to an integer variable. You just use the keyword for the floating-point type that you want to use:

    float Radius;
    double Biggest;

    If you need to store numbers with up to seven digits of accuracy (a range of 10-38to+38), then you should use variables of type float. Values of type float are known as single precision floating-point numbers. This type will occupy 4 bytes in memory, as you can see from the table. Using variables of type double will allow you to store double precision floating-point values. Each variable of type double will occupy 8 bytes in memory and give you 15-digit precision with a range of 10-308to 10+308. Variables of type double suffice for the majority of requirements, but some specialized applications require even more accuracy and range. The long double type provides the exceptional range and precision shown in the table.

    To write a constant of type float, you append an f to the number to distinguish it from type double. You could have initialized the last two variables with these statements:

    float Radius = 2.5f;
    double Biggest = 123E30;

    The variable Radius has the initial value 2.5, and the variable Biggest is initialized to the number that corresponds to 123 followed by 30 zeroes. Any number that you write containing a decimal point is of type double unless you append the F to make it type float. When you specify an exponent value with E or e, the constant need not contain a decimal point. For instance, 1E3f is of type float and 3E8 is of type double.

    To specify a long double constant, you need to append an upper- or lowercase letter L to the number, for example:

    long double huge = 1234567.89123L;

    This article is excerpted from Beginning C by Ivor Horton (Apress, 2004; ISBN 1590592530). Check it out at your favorite bookstore today. Buy this book now.

    More Code Examples Articles
    More By Apress Publishing


     

    CODE EXAMPLES ARTICLES

    - Handling Animations and Bitmaps Using GDI+ f...
    - Download a Web Page using the WebClient
    - Creating a Chart using Data from a Database ...
    - The Basics of Charting with the MS Chart Con...
    - Searching Body Text with textRange: Enter th...
    - Searching Body Text with textRange: Building...
    - Searching Body Text with textRange, part 1: ...
    - First Steps in Programming
    - Programming in C
    - Quick Introduction to ASF,ASX, and Networkin...
    - SatView: Pointer Perfect, Part 2: Constructi...
    - SatView: Pointer Perfect, Part 1
    - Style Case Studies: Construction Unions
    - Creating an Engine for Games for Windows
    - Style Case Studies: Generic Callbacks





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway