variables, data types, and more… introduction in this ... · decimal point distinguished from...

22
Variables, Data Types, and More… Introduction In this lesson will introduce and study 9 C annotation and comments 9 C variables 9 Identifiers 9 C data types 9 First thoughts on good coding style 9 Declarations vs. definitions 9 Initializations vs. assignment 9 Implicit and explicit conversion between types Annotation and Comments – A First Look Important part of any program Annotation Comments Annotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments Section may comprise Function Portion of an algorithm Code fragment Etc. Possible things to include Name of function, module, or file Author’s name Revision level and / or date Description of the code Description of major functions Date, description of any modifications, and initials of author Annotation also includes some of same language considerations We will discuss under comments We start with several major annotation blocks - 1 of 22 -

Upload: lammien

Post on 11-Aug-2019

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Variables, Data Types, and More… Introduction

In this lesson will introduce and study C annotation and comments C variables Identifiers C data types First thoughts on good coding style Declarations vs. definitions Initializations vs. assignment Implicit and explicit conversion between types

Annotation and Comments – A First Look

Important part of any program • Annotation • Comments

Annotation

Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments

Section may comprise Function Portion of an algorithm Code fragment Etc.

Possible things to include Name of function, module, or file Author’s name Revision level and / or date Description of the code Description of major functions Date, description of any modifications, and initials of author

Annotation also includes some of same language considerations

We will discuss under comments

We start with several major annotation blocks

- 1 of 22 -

Page 2: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Examples Annotation at Start of Files

//----------------------------------------------------------- // Module name: // filename.c // // Description: // Function counts the number of lines in a C source file.

// Does not count blank lines or comment lines. // Reports the results to stdout. Also saves the results // in a data file for further use. // // Author: // Your Name // Rev. 0 15 March 2013 //-----------------------------------------------------------

Annotation at the Start of Functions and Methods

//----------------------------------------------------------- // SetRadius // // Purpose: // Sets the radius of the circle. // // Parameters: // [in] double radius - the radius value to set // // Returns: // bool - true if the function succeeds // // Method: // Copies the input value to a local variable

// // Author:

// Your Name // Rev. 0 15 March 2013 //-----------------------------------------------------------

- 2 of 22 -

Page 3: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Annotation at the Start of Test Output //----------------------------------------------------------- // Module Name: // CircleArea // // Description: // Test that area of a circle computed and returned correctly // for several sizes of radius over the permissible range of

// values. //

// Author: // Your Name // Rev. 0 15 March 2013 //----------------------------------------------------------- Comment

Comment is piece of text accompanying piece of code To provide explanation of

• Description of line or block of code • Purpose of line of code • Elaboration on what code is doing • Notes to future modifiers of code • In general any information designer feels necessary

C language supports two styles of comment

Single line Code // comment text

All text following // on same line Interpreted as comment

or Code /* comment text */

All text following opening /* and closing */ Interpreted as comment

- 3 of 22 -

Page 4: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Multi line Code /* comment text

more comment text yet comment text still more comment text enough comment text */

or Code /*

comment text more comment text yet comment text still more comment text enough comment text

*/

All text following opening /* and closing */ Interpreted as comment

Caution Be careful with the C style /* …. */ comment delimiters… What’s wrong with the following code fragment

Code0 /* comment text more comment text yet comment text

still more comment text enough comment text

Code1

Code2 /* comment text more comment text yet comment text still more comment text enough comment text

*/

When comments are used in program Should always be aligned

- 4 of 22 -

Page 5: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Example: Poor style

int x = 9; // initialize x int y = 91; // initialize z int z = 910; // initialize z

Good Style

int x = 9; // initialize x int y = 91; // initialize z int z = 910; // initialize z

Comments should always be suggestive of their intended purpose. Example

Poor style

int x = 9; // set x to 9

Comment provides no information useful information

Good style int timer1Init = 0x12; // initialize timer1 to 12 ms

Better style

int timer1Init = 12MS; // initialize timer1 to 12 ms Here 12MS was declared earlier either as

Const integer Symbolic constant

Using earlier #define directive

All variable and function names should be suggestive of their intended purpose

Example int x = 9; // poor style int timer1Init = 0x12; // good style void f1 ( char* p1 ) // poor style void parseCommand ( char* recBufPtr ) // good style

- 5 of 22 -

Page 6: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Identifiers and Variables Let’s now revisit and explore C variables in greater depth

You may be familiar with many of these from other studies

Have noted programs encapsulate Data and functions

In various ways Examine these in greater depth

All such called identifiers Identifier is the name of the variable or function

Identifiers include Variables

These are data that can be changed Constants also called symbolic constants

These are data than cannot be changed Sometimes call constants variables as well

Strange – a variable that is a constant Function Names

These operate on data

Legal Identifiers Identifier

Comprised of string of characters Include

Letters Upper case Lower case

Digits 0..9

Underscore _

No other characters First Character must be

Letter Underscore

Typically don’t use Reserved for library functions

By tradition May have conflict otherwise

- 6 of 22 -

Page 7: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Cannot be C keyword

Case Significant x, X are different names

Length ANSI Standard

First 31 characters valid or unique - local variables

External names Function call

First 6 characters guaranteed to be unique myFunction0() and myFunction1()

May compile to same function name myFunc() Depends upon compiler

Some implementations support more

Must be aware of this Affects portability

Most systems Accept 31 for external vars as well

Selecting Identifiers

Rules of thumb When selecting identifiers choose name

That is meaningful That is relevant to working context Self explanatory Easy to understand and work with

Should never use

Names of body parts Names of bodily functions Names of reproductive processes Your opinion of

The design Programming language Members of your team

- 7 of 22 -

Page 8: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Spelling the identifier name Variety of different spelling methods No particular method is right or wrong Which ever you choose – be consistent

Example All lowercase

int motorspeed = 100; Can be difficult to read

Uppercase each major word

int motorSpeed = 100; Sometimes called camel notation

Separate each major word with a dash

int motor-speed = 100; Separate each major word with an underscore

int motor_speed = 100;

In addition to suggestions above

Should take several other things into account Unless you are one of the very rare designers

The ones whose design works perfectly the first time Will need to have several passes through debug stage

Process of debugging typically means frequent searches through the code Consider following declarations

int i = 9; int z = 8;

Are these two equivalent

They seem to be Which one might be worse – why?

Now consider searching your code for either variable

Which will be the easier to find In a typical program

How many instances of

- 8 of 22 -

Page 9: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

‘i’ might you find ‘z’ might you find

Next consider

int motorSpeed = 100; int speedOfMotorWhenInputVoltageAtMaximumValue = 100;

Which identifier is easier to work with and why Do you want to try to search for that second name?

Data Types

Variables Types and Sizes Basic Types - 4

char Single byte - 8 bits Holds one character

int integer - typically 32 bits on today’s machines Reflects natural size of ints on host machine

Depending on the machine maybe 8, 16, 64 float

Single precision floating point number - typically 32 bits double

Double precision floating point number - typically 64 bits Modifiers

Following table identifies Base type Qualifiers that modify that type

Early motivation Save memory

Memory was limited and expensive Again machine dependent Assuming a 16 bit int here

- 9 of 22 -

Page 10: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Base Type Modifier Typical Length Expressive Power Example Declaration

int short 8 28 → 256 short int lowerLimit long 32 232 → 4.3 x 10 9 long int upperLimit

(signed by default) signed - 16 bits → 32 767 signed int lowerLimit (msb is sign) - 32 bits → 2.2 x 10 9 signed long upperLimit

unsigned - 16 bits → 65 535 unsigned int arraySize

char short not applicable long not applicable

(msb is sign) signed 8 128 → -128 to +127 signed char error = -1 unsigned 8 256 → 0 to 255 unsigned char success = 1

float short not applicable long not applicable (signed by default) signed 32 6 significant digits float pi = 3.14 unsigned not applicable

double short not applicable long 128

signed

machine dependent

20 significant digits long double pi = 3.1415...

(signed by default) signed 64 10 significant digits double pi = 3.1415... unsigned not applicable

Representation - float / double Different from ints

3 parts - typical representation sign bit 0 exponent bits 1 - 8 fraction bits 9 - 31 or 9 - 63

Expressive power

(- 2 24 to 2 24 - ) x 2 7 -1 ⇒ 1 x 10 ± 37

Fraction max = 0.9999... Exponent

- 10 of 22 -

Page 11: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Usually encoded Desire to store as positive number

Excess subtracted when retrieved

Two files with all ANSI compliant compilers contain <limits.h>

Specifications for integral types <float.h>

Specifications for floating point types These files include

Basic variable sizes Machine and compiler dependent properties

Declarations and Definitions All variables

Must be declared before use Some variables

Must be defined before use

Declaration Introduces the variable name to the program

Definition Allocates memory to store the variable

Declaration specifies Type One or more variables of that type

Example

int lower, upper, step; char c;

Can also write

int lower; int upper; int step;

- 11 of 22 -

Page 12: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Initialization and Assignment Initialization

Variable may be initialized at time it is defined Given an initial value

Defined is correct word Must be memory space to hold the initializing value

Example

int lower = 3, upper, step; char c = ‘b’;

Initialization done only once

Start of execution

Const Qualifier Some variables must be initialized when they are defined Qualifier const

Specifies variables’ value not to be changed Can be applied to definition of any variable

Const qualified variable

Must be initialized at time of definition

Example

const int lower = 3; int upper = 10; // upper can be changed here

int checkLimit (const int upper) {

Function cannot change the argument upper }

Example const int lower = 3; // an initialization

lower = lower + 1; // an attempted assignment

Compile error - cannot modify const object

- 12 of 22 -

Page 13: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Example const int lower; // variable not initialized – has unknown value, not 0

lower = 3; // an attempted assignment

Compile error - cannot modify const object

Constants Constants are identifiers whose values are not expected to change Typically written upper case

Distinguish from variables Distinguish from class names in C++

Typical upper case first letter

Example PI with the value 3.1417 #define PI 3.1417

Now use PI in program

Preprocessor will substitute the number 3.1417

Note: An error to try to change a constant

Place #define statements before main

Constant Types

Type Write

int #define INT_CONSTANT 1234

long #define LONG_CONSTANT 1234l or 1234L

unsigned #define US_CONSTANT 1234u, 1234ul, or 1234uL

float #define FLOAT_CONSTANT 1.2f or 1.2F

long double #define LDOUBLE_CONSTANT 1.2l or 1.2L decimal point distinguished from long int

char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character in the machine’s character set

string #define STRING_CONSTANT “Sept Oct Nov”

- 13 of 22 -

Page 14: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Assignment Variable can be

Initialized one time Assigned to multiple times

Example

int x = 5; // x is initialized to 5 x = 7; // x is assigned the value 7

Lvalues and Rvalues Terms lvalue and rvalue

Qualify which variables can be Initialized Assigned to

rvalue

Can only appear on the right hand side of an assignment statement lvalue

Can appear on the right hand or left hand side of an assignment statement Example

// x is an lvalue and it appears on the left hand side of the assignment int x = 5; // y is an lvalue and it appears on the left hand side of the assignment int y = 8; // x is an lvalue and it appears on the left hand side of the assignment // y is an lvalue but it appears on the right hand side of the assignment x = y; // 3 is an rvalue // it cannot appear on the left hand side of the assignment 3 = x.

- 14 of 22 -

Page 15: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Magic Numbers Variable definitions and initializations of form

int motorSpeed = 100; // set motorSpeed to 100

said to be using magic numbers In this case value 100

Definition above has several style problems • Uses magic number as initializer • Comment provides no useful information not already contained in definition

Preferred method for definition

Change magic number to symbolic constant Provide useful information in comment

Example

#define MAXSPEED 100 int motorSpeed = MAXSPEED; // set motor to full speed In this case does not provide significantly more information

Than can be seen by self-documenting definition

Type Conversions We have learned that variable’s type

Provides various kinds of useful and necessary information about the variable • Its size – number of bits • Signed or unsigned • Simple or complex

Such information helps to ensure that we are using

Proper ‘kind’ of data for our statement or application int rather than pointer to int char rather than int float rather than char

In our statements, expressions, algorithms

Normally want to ensure All variables of same type

- 15 of 22 -

Page 16: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Are times when need to be able to convert From one type to another Why…..

Consider simple problem of adding $5.25 and $2 First number is of type float and second is of type int

These are different – but we typically don’t think about it Should be able to easily add the two amounts however

…and we do without thinking To perform addition

Mentally convert $2 to $2.00 Convert second number from int type to float type Perform addition

Such an operation called implicit conversion C language supports two kinds of conversion

• Implicit As we’ve just seen Done secretly by compiler

• Explicit We as programmer tell compiler

What kind of conversion we want Let’s examine each of these

See how they work

We’ll begin with discussion Implicit type conversions In contrast to explicit conversions

Implicit Type Conversions An implicit type conversion occurs

When the compiler needs to convert data From one intrinsic type To data of another intrinsic type

Implicit conversions that preserve values

Commonly called promotions Before an arithmetic operation is performed

- 16 of 22 -

Page 17: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Integral promotion is used to create ints Out of shorter integral types and

Floating-point promotion to make doubles Out of floats

Promotions will not promote

To long or to long double

The integral promotions are • char, signed char, unsigned char, short int, or unsigned short int

Convert to int

• bool converts to int false becomes 0 and true becomes 1

Let’s look at several conversions

Integral Promotions

Example Let’s look at the following simple program

implicitConvert0.c

#include <stdio.h> int main(void) { // declare some variables short myShort = 2; int myInt = 3; myInt = myShort; printf(“%d \n”, myInt); // prints 2 myInt = 3; myShort = myInt; printf(“%d \n”, myInt); // prints 3 myInt = 32767; myShort = myInt; printf(“%d \n”, myShort); // prints 37767

- 17 of 22 -

Page 18: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

myInt = 100000; myShort = myInt; printf(“%d \n”, myShort); // prints -31072 return 0; }

The assignment of myShort to myInt is safe myInt = myShort

Because a short

Typically (16 bits) on 32 bit machine Can fit inside an int

32 bits on 32 bit machine The first assignment of myInt to myShort is somewhat safe

myShort = myInt

For this particular assignment Why

Will probably generate a warning when you compile In this example

Value of myInt is 3 Can be expressed in fewer than 16 bits

In fact could have int as large as 32767 Will still work

Since 216 is 65536

What will display if we assign value 65536 to the int Then assign the int to the short

What will display if we assign value 100000 to the int

Then assign the int to the short What are the dangers of this implicit conversion

Floating Point Conversions

Floating-point type conversions Cannot be guaranteed to preserve value

So they are not called promotions

Converting a float to a double is safe But converting a double to a float is only safe

- 18 of 22 -

Page 19: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

If the value in the double will fit in the float If it won't the results are not defined

As with all implicit conversions

Your compiler is not obligated to warn you

Floating point conversion to integer works fine As long as the integer variable is large enough

To hold the resulting value Note:

Fractional portion of the floating point number is truncated Only if the truncated value is

Too large to be represented by the integer type Is the conversion undefined

Side Effect Cast

Implicit conversions Often referred to as side effect cast

Meaning Conversion takes place

As result or part of performing some other operation Such casts can be very dangerous

Why

Explicit Type Conversions We’ve seen that type conversions

Can occur automatically or implicitly casting is a way to explicitly convert data

From one type to another

Note: Value and type of original variable remain unchanged Casting

Creates temp variable of specified type Assigns value of original variable to temp

- 19 of 22 -

Page 20: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Suppose encounter the following code

char data = 'M'; printf(“%c \n”, data);

printf()

Senses the char data type Switches to character mode M appears on the screen

If we really wanted the number corresponding to data

We can rewrite these lines as

char data = 'M'; int displaydata; displaydata = data; // is this a good idea printf(“%d \n”, displaydata);

Now printf()

Senses the int data type Switches to integer mode We see 77 on the screen

We see we had to add an int variable

Solely for the purpose of displaying data That variable will continue to exist until the functions complete

Seems like a waste What is needed

Way to tell the compiler Convert the char type to an int type on the fly

Here is the explicit cast char data = 'M'; printf(“%d \n”, (int)data);

The cast (int)data in the code above

Tells the compiler

- 20 of 22 -

Page 21: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

Make a copy of the data and Make that copy an int

When data is to be sent to printf() Copy is sent instead

printf() now sees an int and displays 77 The reasons for casting are varied

Here are two 1. When we add floating-point numbers

Decimal portions of the numbers are part of the sum If we

Cast the floating-point numbers to integers Then add them

Decimal portions have all been chopped off R

 

esult is the sum of the integer portions only

Example Cast below rounds a floating point sum to the nearest integer value

float cost = (int) (1234.56 + 0.5);

2. We might cast one type to another To produce particular results

As in earlier example When we cast the character 'M' to integer

To produce the integer value 77 on the output

Good Style In general casting can lead to unanticipated side

effects and should be avoided

If you must cause a cast – make it explicit

- 21 of 22 -

Page 22: Variables, Data Types, and More… Introduction In this ... · decimal point distinguished from long int char #define CHAR_CONSTANT ‘1’ or ‘a’ value is numeric value of character

- 22 of 22 -

Summary In this lesson we studied

Several fundamental aspects of C programs Basic mechanics of constructing C programs Some of the basic terminology First thoughts on C annotation, comments, and good coding style C variables and Identifiers C data types Implicit and Explicit conversion between types Concept of type promotions