50
Chapter 3 Chapter 3 The Basic Data The Basic Data Types Types C/C++ Programming C/C++ Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

Chapter 3 The Basic Data Types C/C++ Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

Embed Size (px)

Citation preview

Chapter 3Chapter 3The Basic Data The Basic Data

TypesTypesC/C++ ProgrammingC/C++ Programming

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

2

Basic Data TypesBasic Data Types

When defining a variable you When defining a variable you MUSTMUST specify specify what type data it contains. In C/C++ there what type data it contains. In C/C++ there are seven basic data types:are seven basic data types:

charactercharacter ( ( charchar ) ) wide character ( wide character ( wchar_t wchar_t ) ) integer ( integer ( intint ) ) floating point ( floating point ( floatfloat ) ) double floating point ( double floating point ( doubledouble ) ) Boolean ( Boolean ( boolbool ) ) valueless ( valueless ( voidvoid ) )

3

Basic Data Types Basic Data Types (continued)(continued)

Data Type Memory Range

char 8 bits -128 to 127

wchar_t 16 bits 0 to 65,535

int (16 bit) 16 bits -32,768 to 32,767

int (32 bit) 32 bits -2,147,483,648 to 2,147,483,647

float 32 bits 3.4E -38 to 3.4E +38

double 64 bits 1.7E –308 to 1.7E +308

bool N/A true or false

void N/A valueless

4

VariablesVariablesVariablesVariables are used to store data temporarily in are used to store data temporarily in your program.your program.

When you create a variable your program, When you create a variable your program, underneath the hood, allocates memory from underneath the hood, allocates memory from the operating system for the value you want to the operating system for the value you want to store.store.

Each time you create a Each time you create a variablevariable you will have you will have to define the to define the type of datatype of data that it will be storing. that it will be storing. We define the We define the data typedata type because the operating because the operating system needs to know how much memory to system needs to know how much memory to allocate forallocate for the values you will be storing.the values you will be storing.

5

Variable DeclarationsVariable Declarations

The variable declaration in a program The variable declaration in a program communicates to the compiler the names of communicates to the compiler the names of all variables used in a program.all variables used in a program.

They also tell the compiler what kind of They also tell the compiler what kind of information will be stored in each variable.information will be stored in each variable.

You areYou are required you declare every variable required you declare every variable used in a program.used in a program.

The general syntax is: The general syntax is: type variable_list;type variable_list;

6

Variable Declarations Variable Declarations (continued)(continued)

The The typetype must be a valid data type, and must be a valid data type, and variable_listvariable_list may contain one or more may contain one or more identifier names separated by commas. Here identifier names separated by commas. Here are some examples:are some examples:

The variable name has nothing to do with its The variable name has nothing to do with its type. type.

int i, j, k;char ch, chr;float f, balance;double d;bool hourly;double YearToDateSales;int Day_Of_Year;

7

Variable Declarations Variable Declarations (continued)(continued)

There are three places a variable may be There are three places a variable may be declared:declared:

Inside functions (Inside functions (local variableslocal variables))

In the definition of function In the definition of function parameters parameters ( (formal parametersformal parameters))

Outside of all functions ( Outside of all functions ( global global variablesvariables ) )

8

Local VariablesLocal VariablesLocal variables are declared inside functions. They Local variables are declared inside functions. They can only be used inside the function they are can only be used inside the function they are declared in and do not exist outside that function. declared in and do not exist outside that function. void func(); // prototype for func()

int main() { int x; // local to main()

x = 10; func(); cout << “\n“; cout << x; // displays 10 return 0;}

void func() { // local to func() int x; x = -199; cout << x; // displays -199}

9

Local Variables Local Variables (continued)(continued)

Local variables are created when the function is Local variables are created when the function is called and called and destroyed when the function terminates. The destroyed when the function terminates. The memory needed for local variables is created and memory needed for local variables is created and destroyed in the same way. Local variables destroyed in the same way. Local variables DO DO NOTNOT retain their values between function calls. retain their values between function calls.

Some books call local variables Some books call local variables dynamic dynamic variablesvariables or or automatic variablesautomatic variables. We will stick . We will stick to the term to the term local variableslocal variables..

10

Formal ParametersFormal ParametersA function may have a A function may have a parameter-listparameter-list in in which you define a function’s parameters. which you define a function’s parameters. These are called These are called formal parametersformal parameters..int func1( int first, int last, char ch ){ . . .}

This function has three parameters that will This function has three parameters that will contain data passed to the function when it is contain data passed to the function when it is called. They can be used/modified by the function called. They can be used/modified by the function just like local variables. Like local variables, their just like local variables. Like local variables, their contents is lost when the function terminates. contents is lost when the function terminates.

11

Global VariablesGlobal VariablesGlobalGlobal variables and their contents stay in variables and their contents stay in existence throughout the entire execution of existence throughout the entire execution of the program. the program.

Global variables are declared outside of Global variables are declared outside of functions. Normally they are place at the top functions. Normally they are place at the top of the program before the function of the program before the function main()main()..

They can be accessed by any function in the They can be accessed by any function in the program.program.

12

void func1(); // prototype for func1()void func2(); // prototype for func2()

int count; // this is a global variable

int main() { int i; // this is a local variable for( i = 0; i < 10; i++ ) { count = i * 2; func1(); } return 0;} void func1() { cout << “count: “ << count << end; // access global variable func2();}

void func2() { int count; // this is a local variable for( count = 0; count < 3; count++ ) cout << “.“;}

13

Some Type ModifiersSome Type ModifiersThe The charchar, , intint, and , and doubledouble data types are allowed data types are allowed to have to have modifiersmodifiers preceding them. A preceding them. A modifiermodifier allows you to alter the meaning of the base type. allows you to alter the meaning of the base type. These modifiers are:These modifiers are:

signed signed ((the default for integers and the default for integers and charchar))

unsignedunsigned longlong shortshort

All can be applied to the integer base types. All can be applied to the integer base types. signedsigned and and unsignedunsigned can be applied to the can be applied to the charchar type, and type, and longlong can be applied to the can be applied to the doubledouble type. type.

14

Data Type Memory Range

char 8 bits -128 to 127

unsigned char 8 bits 0 to 255

signed char 8 bits -128 to 127

int 32 bits -2,147,483,648 to 2,147,483,647

unsigned int 32 bits 0 to 4,294,967,295

signed int 32 bits -2,147,483,648 to 2,147,483,647

short int 16 bits -32,768 to 32,767

unsigned short int 16 bits 0 to 65,535

signed short int 16 bits -32,768 to 32,767

long int 32 bits -2,147,483,648 to 2,147,483,647

unsigned long int 32 bits 0 to 4,294,967,295

signed long int 32 bits -2,147,483,648 to 2,147,483,647

float 32 bits 3.4E-38 to 3.4E+38

double 64 bits 1.7E-308 to 1.7E+308

long double 80 bits 3.4E-4932 to 1.1E+4932

bool N/A true or false

wchar_t 16 bits 0 to 65,535

15

Sample ProgramSample Programint main(){ short int i; // a signed short integer short unsigned int j; // an unsigned short integer j = 60000; I = j; cout << I << “ “ << j << endl;

return 0;}

Output:-5536 60000

The value 60000 exceeds the capacity of a short integer and gets interpreted as the value -5536.

16

Type Modifiers Type Modifiers (continued)(continued)

A shorthand notation is allowed unsigned, A shorthand notation is allowed unsigned, short, and long integers.short, and long integers.

Each of these are equivalent:Each of these are equivalent:

short int x; short x;short int x; short x; unsigned short int y; unsigned short y;unsigned short int y; unsigned short y; long int a; long a;long int a; long a; unsigned long int b; unsigned long b;unsigned long int b; unsigned long b; unsigned int c; unsigned c;unsigned int c; unsigned c;

17

char Typeschar TypesA variable of the type char ( A variable of the type char ( char ch;char ch; ) can store ) can store ONLYONLY half of half of the the 256256 character ASCII character set. If you need the character ASCII character set. If you need the capability of representing capability of representing ALLALL the characters of the ASCII the characters of the ASCII character set you must define it as being unsigned ( character set you must define it as being unsigned ( unsigned unsigned

char ch;char ch; ). A ). A charchar type can also hold numeric values type can also hold numeric values equivalent to a “equivalent to a “smallsmall” integer with a range of from ” integer with a range of from -128-128 to to +127+127. .

For example:For example:

int main() { char letter; for( letter = ‘Z’; letter >= ‘A’; letter-- ) cout << letter << endl;

return 0;}

18

LiteralsLiteralsLiteralsLiterals ( also called ( also called constants constants ) refer to fixed values ) refer to fixed values that cannot be changed by the program. They can be of that cannot be changed by the program. They can be of any of the basic data types. How they are represented any of the basic data types. How they are represented determines their specific data type. Here is a summary:determines their specific data type. Here is a summary:

Data Type Examples of Literals

int 1 123 21000 -234

long int 35000L -34L

unsigned int 10000U 987U 40000U

unsigned long 12323UL 900000UL

float 123.23F 4.3e-3F

double 23.23 123123.33 -0.9876324

long double 1001.2L

19

Hexadecimal and Octal Hexadecimal and Octal LiteralsLiterals

You can also create literals that represent both You can also create literals that represent both octaloctal ( base 8 ) and ( base 8 ) and hexadecimalhexadecimal ( base 16 ) numbers. ( base 16 ) numbers. Hexadecimal literals are by far more common than Hexadecimal literals are by far more common than octal values.octal values.

Hexadecimal format: Hexadecimal format: 0x6D0x6D or or 0XFF 0XFF oror 0X1B6C 0X1B6C Octal format………: Octal format………: 012012 or or 057057

Hexadecimal literals have a prefix of Hexadecimal literals have a prefix of 0x0x or or 0X0X followed followed by a hexadecimal number (by a hexadecimal number ( 0123456789ABCDEF0123456789ABCDEF).).

Octal literals have a prefix of a Octal literals have a prefix of a 00 followed by an octal followed by an octal numbernumber

((0123456701234567). ).

20

String and char LiteralsString and char LiteralsA string is a set of characters enclosed by double A string is a set of characters enclosed by double quotes ( quotes ( “”“” ). For example, ). For example, “This is a string “This is a string literal”literal” is an example of a string literal. Remember is an example of a string literal. Remember that C does not have a a built in string data type. C that C does not have a a built in string data type. C uses uses nullnull terminates character arrays to house strings. terminates character arrays to house strings.

Example:Example: “A”“A” – – generatesgenerates

Example:Example: “ABCDEF“ABCDEF”” – – generatesgenerates

A A charchar literal is enclosed by single quotes ( literal is enclosed by single quotes ( ‘’‘’) and ) and generate only one byte of memory.generate only one byte of memory.

Example:Example: ’A’’A’ – – generatesgeneratesA

A B C D E F \0

A \0

21

Character Escape SequencesCharacter Escape SequencesThere are a few escape sequence characters that There are a few escape sequence characters that you can use with you can use with coutcout. . Note the lower case Note the lower case letters.letters.

\a\a Alarm (beeps the speaker).Alarm (beeps the speaker). \b\b Backspace.Backspace. \n\n New line.New line. \t\t Horizontal tab.Horizontal tab. \f\f Form FeedForm Feed \r\r Carriage ReturnCarriage Return \v\v Vertical TabVertical Tab \\\\ BackslashBackslash \?\? Question MarkQuestion Mark \’\’ Single QuoteSingle Quote \”\” Double QuoteDouble Quote \N\N Octal constant (N = octal constant)Octal constant (N = octal constant) \xN\xN Hexadecimal constant (N = hex constant) Hexadecimal constant (N = hex constant)

22

Character Escape SequencesCharacter Escape SequencesExamples:Examples:

cout << ‘\a’;cout << “ABC\bDEF”;

“C:\ABC\XYZ\DATAFILE.TXT”“C:\\ABC\\XYZ\\DATAFILE.TXT”

cout << “Hello World\n”; cout << “\tHello World\n”;

cout << “He said \”Hi\”.”;

23

Variable InitializationsVariable InitializationsAs mentioned earlier you can give a variable an initial As mentioned earlier you can give a variable an initial value when it is declared. The format is:value when it is declared. The format is:

type variable-name = valuetype variable-name = value;;

Examples:Examples: char ch = ‘a’; int first = 0; float balance = 123.23F; double amount = 0.0; int second = first; int x = 5, y, z = 20;

24

Variable InitializationsVariable Initializations

Notes:Notes: Global variables are initialized only at the Global variables are initialized only at the

start of the program.start of the program.

Local variables are initialized each time Local variables are initialized each time the function they are declared in is the function they are declared in is entered.entered.

All global variables are initialized to zero All global variables are initialized to zero if no other initializer is specified.if no other initializer is specified.

Local variables that are not initialized will Local variables that are not initialized will have unknown values (garbage). have unknown values (garbage).

25

OperatorsOperators

C/C++ have C/C++ have MANYMANY built-in operators. An operator built-in operators. An operator is a symbol that tells the compiler to perform a is a symbol that tells the compiler to perform a specific mathematical or logical operations.specific mathematical or logical operations.

The general classes of operators are:The general classes of operators are:

ArithmeticArithmetic RelationalRelational LogicalLogical BitwiseBitwise

There are other special ones that perform particular There are other special ones that perform particular tasks:tasks:

-> & * ?-> & * ?

26

Arithmetic OperatorsArithmetic OperatorsOperator Action

+ Addition- Subtraction, also unary

minus* Multiplication/ Division% Remainder or Modulus-- Decrement++ Increment

27

Arithmetic ExpressionsArithmetic ExpressionsThe operators The operators ++, , --, , **, and , and // may be used with type may be used with type intint or or doubledouble operands. operands.

The data type of the result is the same as the data The data type of the result is the same as the data types of the operands.types of the operands.

The remainder operator ( The remainder operator ( %% ) can be used with integer ) can be used with integer operands to find the remainder of longhand division.operands to find the remainder of longhand division.

When applied to two positive integers, the division When applied to two positive integers, the division operator ( operator ( // ) computes the integral part of the result ) computes the integral part of the result of dividing its first operand by its second.of dividing its first operand by its second.

The division operator is undefined when the divisor is The division operator is undefined when the divisor is 00..

28

Data Type of an ExpressionData Type of an Expression The data type of an expression depends on the The data type of an expression depends on the

type oftype of its operands. its operands.

Examples:Examples: int X = 5;int X = 5; int Y = 10;int Y = 10; X + Y X + Y

The result is of type The result is of type intint if both operands if both operands are are intint’s.’s.

int X = 5;int X = 5; double Y = 10.5; double Y = 10.5; X + YX + Y

The result is a The result is a doubledouble when one operand is when one operand is a typea type intint and the other operand is a type and the other operand is a type doubledouble..

29

Data Type of an ExpressionData Type of an Expression The expression is evaluated before the assignment is The expression is evaluated before the assignment is

made, and the type of the variable being assigned made, and the type of the variable being assigned has no effect whatsoever on the expression value.has no effect whatsoever on the expression value.

Example:Example:

int X = 5;int X = 5; int Y = 10;int Y = 10;double A;double A;

A = Y / X;A = Y / X; The expression The expression Y / XY / X evaluates to an integer. This evaluates to an integer. This

value is converted to type double before it is stored value is converted to type double before it is stored in in AA..

If the data types were reversed the fractional part If the data types were reversed the fractional part of the expression would be lost in the conversion.of the expression would be lost in the conversion.

30

Evaluating ExpressionsEvaluating Expressions Rules for evaluating expressions:Rules for evaluating expressions:

All expressions in parentheses must be evaluated All expressions in parentheses must be evaluated separately. Nested parenthesized expressions separately. Nested parenthesized expressions must be evaluated from the inside out, with the must be evaluated from the inside out, with the innermost expression evaluated first.innermost expression evaluated first.

Operators in the same expression are evaluated Operators in the same expression are evaluated in the following order:in the following order:

Unary +, -Unary +, - *, /, %*, /, % Binary +, -Binary +, -

Unary operators in the same sub expression and Unary operators in the same sub expression and at the same precedence level are evaluated right at the same precedence level are evaluated right to left. Binary operators in the same sub to left. Binary operators in the same sub expression at the same precedence level are expression at the same precedence level are evaluated left to right.evaluated left to right.

31

Compound AssignmentCompound Assignment Assignments that use the old value of a variable to Assignments that use the old value of a variable to

compute its new value are commonly used in C compute its new value are commonly used in C programs.programs.

Example:Example: Counter = Counter + 1;Counter = Counter + 1;

C’s compound assignment operators allow us to shorten C’s compound assignment operators allow us to shorten this statement.this statement.

The general syntax is:The general syntax is: variable operator value;variable operator value;

The operators can be:The operators can be: +=+= Adds the value to the variable.Adds the value to the variable. -=-= Subtracts the value to the variable.Subtracts the value to the variable. *=*= Multiplies the value with the variable.Multiplies the value with the variable. /=/= Divides the value to the variable. Divides the value to the variable. %=%= Computes the remainder when the variable is Computes the remainder when the variable is

divideddivided by the value, the result is then stored in the by the value, the result is then stored in the variable.variable.

32

Increment and Decrement Increment and Decrement OperatorsOperators

The counting loops that you have seen have The counting loops that you have seen have all included assignment expressions in the all included assignment expressions in the form of:form of: Counter = counter + 1;Counter = counter + 1; Counter += 1;Counter += 1;

The increment and decrement operators are:The increment and decrement operators are: ++++ IncrementIncrement ---- DecrementDecrement

The increment and decrement operators The increment and decrement operators take a single variable as their operand. take a single variable as their operand.

33

Increment and Decrement Increment and Decrement OperatorsOperators

The The ++++ operator increments its operand by the operator increments its operand by the value of value of 11..

The The ---- operator decrements its operand by the operator decrements its operand by the value of value of 11..

Examples:Examples: ++counter; ++counter; oror counter++; counter++; --counter; --counter; oror counter--; counter--;

The value of the expression in which the The value of the expression in which the ++++ or or -- -- operator is used depends on the position of operator is used depends on the position of the operator.the operator.

34

Post verses Pre Increment Post verses Pre Increment and Decrement Operatorsand Decrement Operators

When the When the ++++ is placed immediately in front is placed immediately in front of its operand of its operand ((prefix incrementprefix increment)), the , the value of the variable is increased by value of the variable is increased by 11 before the variable is used in any before the variable is used in any expression.expression.

When the When the ++++ is placed immediately after its is placed immediately after its operand operand ((postfix incrementpostfix increment)), the value of , the value of the variable is increased by the variable is increased by 11 after the after the variable is used in any expression.variable is used in any expression.

35

Post verses Pre Increment Post verses Pre Increment and Decrement Operatorsand Decrement Operators

Examples:Examples: int x = 0;int y = 1;

cout << x++; // displays 0x = 0;cout << ++x; // displays 1

36

Precedence of Arithmetic Precedence of Arithmetic OperatorsOperators

Highest ++ --

- (unary minus)

* / %

Lowest + -

37

Relational and Logical Relational and Logical OperatorsOperators

RelationalRelational refers to relationship that values have with refers to relationship that values have with oneone another. another.

LogicalLogical refers to the ways in which true and false values refers to the ways in which true and false values may be connected together. may be connected together.

The outcome of a relational or logical operation is a The outcome of a relational or logical operation is a boolbool,, which can be either which can be either truetrue (automatically converted to the (automatically converted to the value value 11) or ) or false false (automatically converted to the value (automatically converted to the value 00).).

Any Any non-zero valuenon-zero value is considered is considered truetrue in C/C++. in C/C++.

38

Relational and Logical Relational and Logical OperatorsOperators

Operator Meaning

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

== Equal to

!= Not equal to

Relational Operators:

Operator Meaning

&& AND

|| OR

! NOT

Logical Operators:

39

Truth Table for Logical Truth Table for Logical OperatorsOperators

p q p AND q

p OR q NOT p

0 0 0 0 1

0 1 0 1 1

1 1 1 1 0

1 0 0 1 0

40

Precedence of Relational and Precedence of Relational and Logical OperatorsLogical Operators

Highest !

> >= < <=

== !=

&&

Lowest ||

41

Expressions and Type Expressions and Type ConversionsConversions

Operators, literals, and variables are constituents of Operators, literals, and variables are constituents of expressionsexpressions..

When literals and variables of different types mixed in When literals and variables of different types mixed in ananexpression, they are converted to the same type.expression, they are converted to the same type.

1.1. Integral promotionIntegral promotion - First, all - First, all charchar and and short short intint values are automatically elevated to values are automatically elevated to intint..

2.2. Type promotionType promotion – Second, all operands are – Second, all operands are converted “converted “upup” to the type of the largest ” to the type of the largest operand. This is done on a operation-by-operand. This is done on a operation-by-operation basis.operation basis.

42

Expressions and Type Expressions and Type ConversionsConversions

These conversions apply to the operands of These conversions apply to the operands of most binary operators, including arithmetic, most binary operators, including arithmetic, relational, and equality operators.relational, and equality operators.

If neither operand type is a floating-point type:If neither operand type is a floating-point type:

long intlong int

int int

Note: When a long int and an unsigned int have the same length and one operand is a long int and the other an unsigned int, both are converted to an unsigned long int.

43

Expressions and Type Expressions and Type ConversionsConversions

If the type of either operand is a floating-point type:If the type of either operand is a floating-point type:

long doublelong double

double double

float float

It is legal to convert a It is legal to convert a charchar to a to a doubledouble or an or an intint to a to a floatfloat..

Once a conversion has been applied, each pair of Once a conversion has been applied, each pair of operands will be of the same type, and the result of operands will be of the same type, and the result of each operations will be the same as the type of both each operations will be the same as the type of both operands.operands.

44

Conversion During AssignmentConversion During Assignment C/C++ follows the simple rule that the C/C++ follows the simple rule that the expression on the right sight of the assignment expression on the right sight of the assignment is converted to the type of the variable on the is converted to the type of the variable on the left side.left side.

char c;char c;

int i;int i;

float f;float f;

double d;double d;

i = c;i = c; // c is converted to int// c is converted to int

f = i;f = i; // i is converted to float// i is converted to floatd = f;d = f; // f is converted to double// f is converted to double

45

Conversion During AssignmentConversion During Assignment Assigning a floating-point number to an Assigning a floating-point number to an integer variable drops the fractional part of integer variable drops the fractional part of the number:the number:

int i;int i;

i = 842.97;i = 842.97; // i is now 842// i is now 842

i = -842.97;i = -842.97; // i is now –842// i is now –842

46

Conversion During AssignmentConversion During Assignment Assigning a value to a variable of a Assigning a value to a variable of a narrowernarrower type will give a meaningless result (or worse) type will give a meaningless result (or worse) if the value is outside the range of the if the value is outside the range of the variable's type (the compiler usually gives a variable's type (the compiler usually gives a warning message):warning message):

char c;char c;int i;int i;float f;float f;

c = 10000c = 10000 // *** wrong ***// *** wrong ***i = 1.0e20;i = 1.0e20; // *** wrong ***// *** wrong ***f = 1.0e100f = 1.0e100 // *** wrong ***// *** wrong ***

47

Converting to and from boolConverting to and from bool Values of type Values of type boolbool are automatically are automatically converted into the integers converted into the integers 0 0 or or 11 when used when used in an integer expression.in an integer expression.

When an integer result is converted to type When an integer result is converted to type boolbool,, 0 0 becomes becomes falsefalse and a and a non-zeronon-zero value value becomes becomes true.true.

48

CastsCasts A A castcast allows you to force an expression to be allows you to force an expression to be of a specific type. of a specific type.

Format:Format: (type-name) expression(type-name) expression

type-nametype-name is the type to which the expression is the type to which the expression is to be converted. For example, the following is to be converted. For example, the following expression forces its result to be a expression forces its result to be a floatfloat instead instead of an of an intint.. int x;int x; (float) x / 2(float) x / 2

Casts are often considered operators. As an Casts are often considered operators. As an operator, a cast is operator, a cast is unaryunary and has the same and has the same precedence as any other unary operator.precedence as any other unary operator.

49

CastsCasts (continued)(continued)

Examples:Examples: float f = 45.678, frac-part;float f = 45.678, frac-part;

frac-part = (int)f; frac-part = (int)f; // frac-part = 45// frac-part = 45

float quotient;float quotient;

int dividend = 7, divisor = 3;int dividend = 7, divisor = 3;

quotient = dividend / divisor; quotient = dividend / divisor; // result 2// result 2

Since Since dividenddividend and and divisordivisor are are intint's above, 's above, quotientquotient will contain only the whole number will contain only the whole number portion ( portion ( 22 ) and no decimal places. The ) and no decimal places. The solution is below: solution is below: quotient = (float)dividend / divisor;quotient = (float)dividend / divisor;

50

Spacing and ParenthesesSpacing and Parentheses

Expressions may have spaces and tabs to Expressions may have spaces and tabs to enhance readability, for example:enhance readability, for example: x=10/y*(127/x); x=10/y*(127/x); // not very readable// not very readable

xx = 10 / y * (127 / x); = 10 / y * (127 / x); // much better// much better

Redundant or additional parentheses will not Redundant or additional parentheses will not cause errors or slow execution of the expression. cause errors or slow execution of the expression. You are encouraged to use parentheses to make You are encouraged to use parentheses to make clear the exact order of an expression’s clear the exact order of an expression’s evaluation. Which as these is easier to read?evaluation. Which as these is easier to read? x = y/3-34*temp+127;x = y/3-34*temp+127;

xx = (y / 3) – (34 * temp) + 127;= (y / 3) – (34 * temp) + 127;