Home > Articles > Programming > C/C++

This chapter is from the book

Variables

A variable is a name for some bytes of memory in a program. When you assign a value to a variable, what you are really doing is storing that value in those bytes. Variables in a computer language are like the nouns in a natural language. They represent items or quantities in the problem space of your program.

C requires that you tell the compiler about any variables that you are going to use by declaring them. A variable declaration has the form

variabletype name;

C allows multiple variables to be declared in a single declaration:

variabletype name1, name2, name3;

A variable declaration causes the compiler to reserve storage (memory) for that variable. The value of a variable is the contents of its memory location. The next chapter describes variable declarations in more detail. It covers where variable declarations are placed, where the variables are created in memory, and the lifetimes of different classes of variables.

Integer Types

C provides the following types to hold integers: char, short, int, long, and long long. Table 1.1 shows the size in bytes of the integer types on 32- and 64-bit executables on Apple systems.

Table 1.1. The Sizes of Integer Types on iOS and Mac OS X

Type

32-Bit

64-Bit

char

1 byte

1 byte

short

2 bytes

2 bytes

int

4 bytes

4 bytes

long

4 bytes

8 bytes

long long

8 bytes

8 bytes

The char type is named char because it was originally intended to hold characters, but it is frequently used as an 8-bit integer type.

An integer type can be declared to be unsigned:

unsigned char a;
unsigned short b;
unsigned int c;
unsigned long d;
unsigned long long e;

When used alone, unsigned is taken to mean unsigned int:

unsigned a;  // a is an unsigned int

An unsigned variable’s bit pattern is always interpreted as a positive number. If you assign a negative quantity to an unsigned variable, the result is a very large positive number. This is almost always a mistake.

Floating-Point Types

C’s floating-point types are float, double, and long double. The sizes of the floating-point types are the same in both 32- and 64-bit executables:

float aFloat;   // floats are 4 bytes
double aDouble; // doubles are 8 bytes
long double aLongDouble;  // long doubles are 16 bytes

Floating-point values are always signed.

Truth Values

Ordinary expressions are commonly used for truth values. Expressions that evaluate to zero are considered false, and expressions that evaluate to non-zero are considered true (see the following sidebar).

Initialization

Variables can be initialized when they are declared:

int a = 9;

int b = 2*4;

float c = 3.14159;

char d = 'a';

A character enclosed in single quote marks is a character constant. It is numerically equal to the encoding value of the character. Here, the variable d has the numeric value of 97, which is the ASCII value of the character a.

Pointers

A pointer is a variable whose value is a memory address. It “points” to a location in memory.

You declare a variable to be a pointer by preceding the variable name with an * in the declaration. The following code declares pointerVar to be a variable pointing to a location in memory that holds an integer:

int *pointerVar;

The unary & operator (“address-of” operator) is used to get the address of a variable so it can be stored in a pointer variable. The following code sets the value of the pointer variable b to be the address of the integer variable a:

1  int a = 9;
2
3  int *b;
4
5  b = &a;

Now let’s take a look at that example line by line:

  • Line 1 declares a to be an int variable. The compiler reserves 4 bytes of storage for a and initializes them with a value of 9.
  • Line 3 declares b to be a pointer to an int.
  • Line 5 uses the & operator to get the address of a and then assigns a’s address as the value of b.

Figure 1.1 illustrates the process. (Assume that the compiler has located a beginning at memory address 1048880.) The arrow in the figure shows the concept of pointing.

Figure 1.1

Figure 1.1. Pointer variables

The unary * operator (called the “contents of” or “dereferencing” operator) is used to set or retrieve the contents of a memory location by using a pointer variable that points to that location. One way to think of this is to consider the expression *pointerVar to be an alias, another name, for whatever memory location is stored in the contents of pointerVar. The expression *pointerVar can be used to either set or retrieve the contents of that memory location. In the following code, b is set to the address of a, so *b becomes an alias for a:

int a;
int c;
int *b;

a = 9;

b = &a;

c = *b;  // c is now 9

*b = 10; // a is now 10

Pointers are used in C to reference dynamically allocated memory (see Chapter 2, “More about C Variables”). Pointers are also used to avoid copying large chunks of memory, such as arrays and structures (discussed later in this chapter), from one part of a program to another. For example, instead of passing a large structure to a function, you pass the function a pointer to the structure. The function then uses the pointer to access the structure. As you will see later in the book, Objective-C objects are always referenced by pointer.

Generic Pointers

A variable declared as a pointer to void is a generic pointer:

void *genericPointer;

A generic pointer may be set to the address of any variable type:

int a = 9;
void *genericPointer;
genericPointer = &a;

However, trying to obtain a value from a generic pointer is an error because the compiler has no way of knowing how to interpret the bytes at the address indicated by the generic pointer:

int a = 9;
int b;
void *genericPointer;
genericPointer = &a;
b = *genericPointer;  // WRONG - won't compile

To obtain a value through a void* pointer, you must cast it to a pointer to a known type:

int a = 9;
int b;
void *genericPointer;
genericPointer = &a;
b = *((int*) genericPointer) ;  // OK - b is now 9

The cast operator (int*) forces the compiler to consider genericPointer to be a pointer to an integer. (See Conversion and Casting later in the chapter.)

C does not check to see that a pointer variable points to a valid area of memory. Incorrect use of pointers has probably caused more crashes than any other aspect of C programming.

Arrays

A C array is an ordered collection of elements of the same type. C arrays are declared by adding the number of elements in the array, enclosed in square brackets ([]), to the declaration, after the type and array name:

int a[100];

Individual elements of the array are accessed by placing the index of the element in [] after the array name:

a[6] = 9;

The index is zero-based. In the previous example, the legitimate indices run from 0 to 99. Access to C arrays is not bounds checked on either end. C will blithely let you do the following:

int a[100];
a[200] = 25;
a[-100] = 30;

Using an index outside of the array’s bounds lets you trash memory belonging to other variables, resulting in either crashes or corrupted data. Taking advantage of this lack of checking is one of the pillars of mischievous malware.

The bracket notation is just a nicer syntax for pointer arithmetic. The name of an array, without the array brackets, is a pointer variable pointing to the beginning of the array. These two lines are completely equivalent:

a[6] = 9;

*(a + 6) = 9;

When compiling an expression using pointer arithmetic, the compiler takes into account the size of the type the pointer is pointing to. If a is an array of int, the expression *(a + 2) refers to the contents of the 4 bytes (one int worth) of memory at an address 8 bytes (two int) beyond the beginning of the array a. However, if a is an array of char, the expression *(a + 2) refers to the contents of 1 byte (one char worth) of memory at an address 2 bytes (two char) beyond the beginning of the array a.

Multidimensional Arrays

Multidimensional arrays are declared as follows:

int b[4][10];

Multidimensional arrays are stored linearly in memory by rows. Here, b[0][0] is the first element, b[0][1] is the second element, and b[1][0] is the eleventh element.

Using pointer notation:

b[i][j]

may be written as

*(b + i*10 + j)

Strings

A C string is a one-dimensional array of bytes (type char) terminated by a zero byte. A constant C string is coded by placing the characters of the string between double quote marks (""):

"A constant string"

When the compiler creates a constant string in memory, it automatically adds the zero byte at the end. But if you declare an array of char that will be used to hold a string, you must remember to include the zero byte when deciding how much space you need. The following line of code copies the five characters of the constant string "Hello" and its terminating zero byte to the array aString:

char aString[6] = "Hello";

As with any other array, arrays representing strings are not bounds checked. Over-running string buffers used for program input is a favorite trick of hackers.

A variable of type char* can be initialized to point to a constant string. You can set such a variable to point at a different string, but you can’t use it to modify a constant string:

char *aString = "Hello";
aString = "World";
aString[4] = 'q';  // WRONG - causes a crash, "World" is a constant

The first line points aString at the constant string "Hello". The second line changes aString to point at the constant string "World". The third line causes a crash, because constant strings are stored in a region of protected, read-only memory.

Structures

A structure is a collection of related variables that can be referred to as a single entity. The following is an example of a structure declaration:

struct dailyTemperatures
  {
    float high;
    float low;
    int   year;
    int   dayOfYear;
};

The individual variables in a structure are called member variables or just members for short. The name following the keyword struct is a structure tag. A structure tag identifies the structure. It can be used to declare variables typed to the structure:

struct dailyTemperatures today;

struct dailyTemperatures *todayPtr;

In the preceding example, today is a dailyTemperatures structure, whereas todayPtr is a pointer to a dailyTemperatures structure.

The dot operator (.) is used to access individual members of a structure from a structure variable. The pointer operator (->) is used to access structure members from a variable that is a pointer to a structure:

todayPtr = &today;

today.high = 68.0;

todayPtr->high = 68.0;

The last two statements do the same thing.

Structures can have other structures as members. The previous example could have been written like this:

struct hiLow
{
    float high;
    float low;
};

struct dailyTemperatures
{
    struct hiLow tempExtremes;
    int   year;
    int   dayOfYear;
};

Setting the high temperature for today would then look like this:

struct dailyTemperatures today;
today.tempExtremes.high = 68.0;

typedef

The typedef declaration provides a means for creating aliases for variable types:

typedef float Temperature;

Temperature can now be used to declare variables, just as if it were one of the built-in types:

Temperature high, low;

typedefs just provide alternate names for variable types. Here, high and low are still floats. The term typedef is often used as a verb when talking about C code, as in “Temperature is typedef’d to float.”

Enumeration Constants

An enum statement lets you define a set of integer constants:

enum woodwind { oboe, flute, clarinet, bassoon };

The result of the previous statement is that oboe, flute, clarinet, and bassoon are constants with values of 0, 1, 2, and 3, respectively.

If you don’t like going in order from zero, you can assign the values of the constant yourself. Any constant without an assignment has a value one higher than the previous constant:

enum woodwind { oboe=100, flute=150, clarinet, bassoon=200 };

The preceding statement makes oboe, flute, clarinet, and bassoon equal to 100, 150, 151, and 200, respectively.

The name after the keyword enum is called an enumeration tag. Enumeration tags are optional. Enumeration tags can be used to declare variables:

enum woodwind soloist;
soloist = oboe;

Enumerations are useful for defining multiple constants, and for helping to make your code self-documenting, but they aren’t distinct types and they don’t receive much support from the compiler. The declaration enum woodwind soloist; shows your intent that soloist should be restricted to one of oboe, flute, clarinet, or bassoon, but unfortunately, the compiler does nothing to enforce the restriction. The compiler considers soloist to be an int, and it lets you assign any integer value to soloist without generating a warning:

enum woodwind { oboe, flute, clarinet, bassoon };
enum woodwind soloist;
soloist  = 5280;  // No complaint from the compiler!

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020