Home > Articles > Programming > C/C++

How to Work with Variables, Data Types, and Arithmetic Expressions in the C Programming Language

C has a rich variety of math operators that you can use to manipulate your data. In this chapter from Programming in C, 4th Edition, Stephen G. Kochan covers the int, float, double, char, and _Bool data types, modifying data types with short, long, and long long, the rules for naming variables, basic math operators and arithmetic expressions, and type casting.
This chapter is from the book

This chapter is from the book

The true power of programs you create is their manipulation of data. In order to truly take advantage of this power, you need to better understand the different data types you can use, as well as how to create and name variables. C has a rich variety of math operators that you can use to manipulate your data. In this chapter you will cover:

  • The int, float, double, char, and _Bool data types
  • Modifying data types with short, long, and long long
  • The rules for naming variables
  • Basic math operators and arithmetic expressions
  • Type casting

Understanding Data Types and Constants

You have already been exposed to the C basic data type int. As you will recall, a variable declared to be of type int can be used to contain integral values only—that is, values that do not contain decimal places.

The C programming language provides four other basic data types: float, double, char, and _Bool. A variable declared to be of type float can be used for storing floating-point numbers (values containing decimal places). The double type is the same as type float, only with roughly twice the precision. The char data type can be used to store a single character, such as the letter ’a’, the digit character ’6’, or a semicolon (’;’) (more on this later). Finally, the _Bool data type can be used to store just the values 0 or 1. Variables of this type are used for indicating an on/off, yes/no, or true/false situation. These one-or-the-other choices are also known as binary choices.

In C, any number, single character, or character string is known as a constant. For example, the number 58 represents a constant integer value. The character string "Programming in C is fun.\n" is an example of a constant character string. Expressions consisting entirely of constant values are called constant expressions. So, the expression

128 + 7 - 17

is a constant expression because each of the terms of the expression is a constant value. But if i were declared to be an integer variable, the expression

128 + 7 – i

would not represent a constant expression because its value would change based on the value of i. If i is 10, the expression is equal to 125, but if i is 200, the expression is equal to −65.

The Integer Type int

In C, an integer constant consists of a sequence of one or more digits. A minus sign preceding the sequence indicates that the value is negative. The values 158, −10, and 0 are all valid examples of integer constants. No embedded spaces are permitted between the digits, and values larger than 999 cannot be expressed using commas. (So, the value 12,000 is not a valid integer constant and must be written as 12000.)

Two special formats in C enable integer constants to be expressed in a base other than decimal (base 10). If the first digit of the integer value is a 0, the integer is taken as expressed in octal notation—that is, in base 8. In that case, the remaining digits of the value must be valid base-8 digits and, therefore, must be 0–7. So, to express the value 50 in base 8 in C, which is equivalent to the value 40 in decimal, the notation 050 is used. Similarly, the octal constant 0177 represents the decimal value 127 (1 × 64 + 7 × 8 + 7). An integer value can be displayed at the terminal in octal notation by using the format characters %o in the format string of a printf() statement. In such a case, the value is displayed in octal without a leading zero. The format character %#o does cause a leading zero to be displayed before an octal value.

If an integer constant is preceded by a zero and the letter x (either lowercase or uppercase), the value is taken as being expressed in hexadecimal (base 16) notation. Immediately following the letter x are the digits of the hexadecimal value, which can be composed of the digits 0–9 and the letters a–f (or A–F). The letters represent the values 10–15, respectively. So, to assign the hexadecimal value FFEF0D to an integer variable called rgbColor, the statement

rgbColor = 0xFFEF0D;

can be used. The format characters %x display a value in hexadecimal format without the leading 0x, and using lowercase letters a–f for hexadecimal digits. To display the value with the leading 0x, you use the format characters %#x, as in the following:

printf ("Color is %#x\n", rgbColor);

An uppercase x, as in %X or %#X, can be used to display the leading x and the hexadecimal digits that follow using uppercase letters.

Storage Sizes and Ranges

Every value, whether it’s a character, integer, or floating-point number, has a range of values associated with it. This range has to do with the amount of storage that is allocated to store a particular type of data. In general, that amount is not defined in the language. It typically depends on the computer you’re running, and is, therefore, called implementation- or machine-dependent. For example, an integer might take up 32 bits on your computer, or perhaps it might be stored in 64. You should never write programs that make any assumptions about the size of your data types. You are, however, guaranteed that a minimum amount of storage will be set aside for each basic data type. For example, it’s guaranteed that an integer value will be stored in a minimum of 32 bits of storage, which is the size of a “word” on many computers.

The Floating Number Type float

A variable declared to be of type float can be used for storing values containing decimal places. A floating-point constant is distinguished by the presence of a decimal point. You can omit digits before the decimal point or digits after the decimal point, but obviously you can’t omit both. The values 3., 125.8, and −.0001 are all valid examples of floating-point constants. To display a floating-point value at the terminal, the printf conversion characters %f are used.

Floating-point constants can also be expressed in scientific notation. The value 1.7e4 is a floating-point value expressed in this notation and represents the value 1.7 × 104. The value before the letter e is known as the mantissa, whereas the value that follows is called the exponent. This exponent, which can be preceded by an optional plus or minus sign, represents the power of 10 by which the mantissa is to be multiplied. So, in the constant 2.25e−3, the 2.25 is the value of the mantissa and −3 is the value of the exponent. This constant represents the value 2.25 × 10−3, or 0.00225. Incidentally, the letter e, which separates the mantissa from the exponent, can be written in either lowercase or uppercase.

To display a value in scientific notation, the format characters %e should be specified in the printf() format string. The printf() format characters %g can be used to let printf() decide whether to display the floating-point value in normal floating-point notation or in scientific notation. This decision is based on the value of the exponent: If it’s less than −4 or greater than 5, %e (scientific notation) format is used; otherwise, %f format is used.

Use the %g format characters for displaying floating-point numbers—it produces the most aesthetically pleasing output.

A hexadecimal floating constant consists of a leading 0x or 0X, followed by one or more decimal or hexadecimal digits, followed by a p or P, followed by an optionally signed binary exponent. For example, 0x0.3p10 represents the value 3/16 × 210 = 0.5.

The Extended Precision Type double

The double type is very similar to the float type, but it is used whenever the range provided by a float variable is not sufficient. Variables declared to be of type double can store roughly twice as many significant digits as can a variable of type float. Most computers represent double values using 64 bits.

Unless told otherwise, all floating-point constants are taken as double values by the C compiler. To explicitly express a float constant, append either an f or F to the end of the number, as follows:

12.5f

To display a double value, the format characters %f, %e, or %g, which are the same format characters used to display a float value, can be used.

The Single Character Type char

A char variable can be used to store a single character.1 A character constant is formed by enclosing the character within a pair of single quotation marks. So 'a', ';', and '0' are all valid examples of character constants. The first constant represents the letter a, the second is a semicolon, and the third is the character zero—which is not the same as the number zero. Do not confuse a character constant, which is a single character enclosed in single quotes, with a character string, which is any number of characters enclosed in double quotes.

The character constant '\n'—the newline character—is a valid character constant even though it seems to contradict the rule cited previously. This is because the backslash character is a special character in the C system and does not actually count as a character. In other words, the C compiler treats the character '\n' as a single character, even though it is actually formed by two characters. There are other special characters that are initiated with the backslash character. Consult Appendix A, “C Language Summary,” for a complete list.

The format characters %c can be used in a printf() call to display the value of a char variable at the terminal.

The Boolean Data Type _Bool

A _Bool variable is defined in the language to be large enough to store just the values 0 and 1. The precise amount of memory that is used is unspecified. _Bool variables are used in programs that need to indicate a Boolean condition. For example, a variable of this type might be used to indicate whether all data has been read from a file.

By convention, 0 is used to indicate a false value, and 1 indicates a true value. When assigning a value to a _Bool variable, a value of 0 is stored as 0 inside the variable, whereas any nonzero value is stored as 1.

To make it easier to work with _Bool variables in your program, the standard header file <stdbool.h> defines the values bool, true, and false. An example of this is shown in Program 5.10A in Chapter 5, “Making Decisions.”

In Program 3.1, the basic C data types are used.

Program 3.1 Using the Basic Data Types

#include <stdio.h>

int main (void)
{

     int       integerVar = 100;
     float     floatingVar = 331.79;
     double    doubleVar = 8.44e+11;
     char      charVar = 'W';

     _Bool     boolVar = 0;


     printf ("integerVar = %i\n", integerVar);
     printf ("floatingVar = %f\n", floatingVar);
     printf ("doubleVar = %e\n", doubleVar);
     printf ("doubleVar = %g\n", doubleVar);
     printf ("charVar = %c\n", charVar);


     printf ("boolVar = %i\n", boolVar);


     return 0;

}

Program 3.1 Output

integerVar = 100
floatingVar = 331.790009
doubleVar = 8.440000e+11
doubleVar = 8.44e+11
charVar = W
boolVar = 0;

The first statement of Program 3.1 declares the variable integerVar to be an integer variable and also assigns to it an initial value of 100, as if the following two statements had been used instead:

int  integerVar;
integerVar = 100;

In the second line of the program’s output, notice that the value of 331.79, which is assigned to floatingVar, is actually displayed as 331.790009. In fact, the actual value displayed is dependent on the particular computer system you are using. The reason for this inaccuracy is the particular way in which numbers are internally represented inside the computer. You have probably come across the same type of inaccuracy when dealing with numbers on your pocket calculator. If you divide 1 by 3 on your calculator, you get the result .33333333, with perhaps some additional 3s tacked on at the end. The string of 3s is the calculator’s approximation to one third. Theoretically, there should be an infinite number of 3s. But the calculator can hold only so many digits, thus the inherent inaccuracy of the machine. The same type of inaccuracy applies here: Certain floating-point values cannot be exactly represented inside the computer’s memory.

When displaying the values of float or double variables, you have the choice of three different formats. The %f characters are used to display values in a standard manner. Unless told otherwise, printf() always displays a float or double value to six decimal places rounded. You see later in this chapter how to select the number of decimal places that are displayed.

The %e characters are used to display the value of a float or double variable in scientific notation. Once again, six decimal places are automatically displayed by the system.

With the %g characters, printf() chooses between %f and %e and also automatically removes from the display any trailing zeroes. If no digits follow the decimal point, it doesn’t display that either.

In the next-to-last printf() statement, the %c characters are used to display the single character 'W' that you assigned to charVar when the variable was declared. Remember that whereas a character string (such as the first argument to printf()) is enclosed within a pair of double quotes, a character constant must always be enclosed within a pair of single quotes.

The last printf() shows that a _Bool variable can have its value displayed using the integer format characters %i.

Type Specifiers: long, long long, short, unsigned, and signed

If the specifier long is placed directly before the int declaration, the declared integer variable is of extended range on some computer systems. An example of a long int declaration might be

long int factorial;

This declares the variable factorial to be a long integer variable. As with floats and doubles, the particular accuracy of a long variable depends on your particular computer system. On many systems, an int and a long int have the same range and either can be used to store integer values up to 32-bits wide (231 − 1, or 2,147,483,647).

A constant value of type long int is formed by optionally appending the letter L (upper- or lowercase) onto the end of an integer constant. No spaces are permitted between the number and the L. So, the declaration

long int numberOfPoints = 131071100L;

declares the variable numberOfPoints to be of type long int with an initial value of 131,071,100.

To display the value of a long int using printf(), the letter l is used as a modifier before the integer format characters i, o, and x. This means that the format characters %li can be used to display the value of a long int in decimal format, the characters %lo can display the value in octal format, and the characters %lx can display the value in hexadecimal format.

There is also a long long integer data type, so

long long int maxAllowedStorage;

declares the indicated variable to be of the specified extended accuracy, which is guaranteed to be at least 64 bits wide. Instead of a single letter l, two ls are used in the printf string to display long long integers, as in "%lli".

The long specifier is also allowed in front of a double declaration, as follows:

long double US_deficit_2004;

A long double constant is written as a floating constant with the letter l or L immediately following, such as

1.234e+7L

To display a long double, the L modifier is used. So, %Lf displays a long double value in floating-point notation, %Le displays the same value in scientific notation, and %Lg tells printf() to choose between %Lf and %Le.

The specifier short, when placed in front of the int declaration, tells the C compiler that the particular variable being declared is used to store fairly small integer values. The motivation for using short variables is primarily one of conserving memory space, which can be an issue in situations in which the program needs a lot of memory and the amount of available memory is limited.

On some machines, a short int takes up half the amount of storage as a regular int variable does. In any case, you are guaranteed that the amount of space allocated for a short int will not be less than 16 bits.

There is no way to explicitly write a constant of type short int in C. To display a short int variable, place the letter h in front of any of the normal integer conversion characters: %hi, %ho, or %hx. Alternatively, you can also use any of the integer conversion characters to display short ints, due to the way they can be converted into integers when they are passed as arguments to the printf() routine.

The final specifier that can be placed in front of an int variable is used when an integer variable will be used to store only positive numbers. The declaration

unsigned int counter;

declares to the compiler that the variable counter is used to contain only positive values. By restricting the use of an integer variable to the exclusive storage of positive integers, the accuracy of the integer variable is extended.

An unsigned int constant is formed by placing the letter u (or U) after the constant, as follows:

0x00ffU

You can combine the letters u (or U) and l (or L) when writing an integer constant, so

20000UL

tells the compiler to treat the constant 20000 as an unsigned long.

An integer constant that’s not followed by any of the letters u, U, l, or L and that is too large to fit into a normal-sized int is treated as an unsigned int by the compiler. If it’s too small to fit into an unsigned int, the compiler treats it as a long int. If it still can’t fit inside a long int, the compiler makes it an unsigned long int. If it doesn’t fit there, the compiler treats it as a long long int if it fits, and as an unsigned long long int otherwise.

When declaring variables to be of type long long int, long int, short int, or unsigned int, you can omit the keyword int. Therefore, the unsigned variable counter could have been equivalently declared as follows:

unsigned counter;

You can also declare char variables to be unsigned.

The signed qualifier can be used to explicitly tell the compiler that a particular variable is a signed quantity. Its use is primarily in front of the char declaration, and further discussion is deferred until Chapter 13, “More on Data Types.”

Don’t worry if the discussions of these specifiers seem a bit esoteric to you at this point. In later sections of this book, many of these different types are illustrated with actual program examples. Chapter 13 goes into more detail about data types and conversions.

Table 3.1 summarizes the basic data types and qualifiers.

Table 3.1 Basic Data Types

Type

Constant Examples

printf chars

char

'a';, '\n'

%c

_Bool

0, 1

%i, %u

short int

%hi, %hx, %ho

unsigned short int

%hu, %hx, %ho

int

12, -97, 0xFFE0, 0177

%i, %x, %o

unsigned int

12u, 100U, 0XFFu

%u, %x, %o

long int

12L, -2001, 0xffffL

%li, %lx, %lo

unsigned long int

12UL, 100ul, 0xffeeUL

%lu, %lx, %lo

long long int

0xe5e5e5e5LL, 500ll

%lli, %llx, &llo

unsigned long long int

12ull, 0xffeeULL

%llu, %llx, %llo

float

12.34f, 3.1e-5f, 0x1.5p10,0x1P-1

%f, %e, %g, %a

double

12.34, 3.1e-5, 0x.1p3

%f, %e, %g, %a

long double

12.341, 3.1e-5l

%Lf, $Le, %Lg

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