Sie sind auf Seite 1von 8

Reading Assignment

Main Program in C
In C the main program is a function called main
The body of the function is enclosed in left (

) and right (

Chapter 2

K.N. King

Chapter 3

K.N. King

Chapter 4

K.N. King

Chapter 7

K.N. King

) curly braces.

In Standard C, the return type of main must be int. If we do not specify the
return type, it defaults to int. We might also be able to get away without
having a return statement.
Good Style: Specify int as the return type for main and always have an
explicit return statement!
There are 3 steps to get a C program from text to executable code:
preprocessing, compiling and linking
If you want to give it a try before the first tutorial, use the following command:
gcc first.c -o first

50

51

Our first C program

C Programming Language

/*******************************************
Name: first.c
Purpose: Prints a traditional C greeting.
Author: Iqbal Mohomed
Date: September 10th 2002
*******************************************/

Very widely used general purpose programming language


Available on many machines and operating systems
Designed to be flexible, powerful, and unconstraining
Originally a replacement for assembly language

C requires extreme care in programming

#include <stdio.h>

C requires really extreme care in programming

int main()
{
/* Print Greeting */
printf("Hello World\n");
return 0;
}

Traditional C and ANSI C

52

C++ is a superset of C with Object Oriented features

53

Good Style: , Good Technique: and WARNING:

BE REALLY REALLY CAREFUL IN C


C provides NO run-time checking

Good Style: indicates a preferred way of programming in C. Programs with

e.g. array subscripts, undefined variables

Good Style: are easier to read, understand, modify and get correct.

Programmer must manage dynamic storage allocation

Markers just love programs that exhibit Good Style: .


Good Technique: indicates a good way to do some particular programming

Pointers are widely used but are unchecked

task in C. The technique is good because its efficient, easy to understand,

Program with extreme care

easy to get correct.

Program with extreme care

An entire slide of Good Technique: usually has HOW TO in the title.

There are good software tools for developing C programs

WARNING: is used to indicate a particularly tricky or dangerous part of C.

debuggers, program checking aids

Good programmers avoid WARNING: constructs or are extremely careful

large libraries of existing software

about how they use them.

54

55

Identifiers (basic names)

Basic Data Types

Identifiers start with a letter or

( underscore )

Use

keyword(s)

constants

integers

unsigned , int , short , long

-237, 0, 23, 101467

real numbers

float , double

-0.123, +417.6, 1234e+7, 0.23e-12

characters

char

a, A, 3, +

Identifiers contain letters, digits or


Upper and lower case letters are distinct, e.g.

A is not the same as a

Examples: i , I , total , bigNumber , DEBUG , testing 123


Words that have a special meaning in C (keywords , See King Table 2.1 ) are
reserved and can not be used as identifiers. Examples: int, while, if
Identifiers are used to name variables, constants, types and functions in C.

Values of type char can be used in integer expressions.

Good Style: Use mnemonic identifiers!!

The character data type is for single characters.

Mnemonic means that the identifier describes its purpose in the program, e.g.

Character strings will be described later.

use sum and index instead of Q and fabulous


Mnemonic identifiers help you (and others) understand what the program is
supposed to do.

Notation: the phrase type-name will be used to denote any valid type in C.
int , double and char are instances of type-name .

56

57

Integer Constants

HOW TO Use Integer Types

Type

Digits

Starts with

Examples

For almost all integer variables, use int

decimal integer

0123456789

1..9

1 123L 456790U

Use short or char when saving space is really important AND ITS KNOWN

octal integer

01234567

01 0123 0456707U

that the range of values for the variable will fit in -32768 .. 32767.

hexadecimal integer

01234567899 abcdef ABCDEF

0x or 0X

0x14 0x123 0XDEADBEEF

Short or char integer variables may be slower to access.


On a few machines long is 64 bits and provides a much larger range of

Add an upper case L after a constant to force it to be treated as a long number.


Good Style: Dont use lowercase l (el), it looks like 1 (one).

values. Dont assume long is larger than int unless you check.

Add an upper case U after a constant to force it to be treated as an unsigned number.

Use unsigned for STRICTLY NON-NEGATIVE integer values.

WARNING: numbers starting with 0 (zero) are octal constants.

For maximum portability use:

( 01238

123 and 0123 have different values.

8310 )

int or short int


long int

for integers in the range -32768 .. 32767


for all other integers
sizeof( int )

58

59

Character and String Constants

Variables and Types

Type

Contains

Starts and

character

a single character

string

arbitrary characters

(single quote)
(double quote)

Examples

ends with

C standard only requires: sizeof( short )

sizeof( long )

Variables are the basic containers used to hold data in C.


Every variable must be declared before it is used.

a @ 1 C

Every variable is associated with a specific type.


abc CSC181F arbitrary

The type of a variable determines the kind of values that it can hold and the
The backslash (

\ ) notation can be used to create character or string constants

containing arbitrary non-printable characters.


See Escape Sequences in King Section 7.3.

amount of storage that is allocated for the variable.


scalar variables can hold exactly one variable at a time. Non-scalar variables
(e.g. arrays) can hold many different values at the same time.

WARNING: be careful to use character constants where a single character is required and
string constants where a string is required.

60

61

Declarations for Scalar Variables


HOW TO Check for Uninitialized Variables

The declaration for a scalar variables has the form


type-name identifierList a
Examples:

int I , J , K

In C a variable can receive a value in one of three waysa

char tempChar , nextChar

A variable can be declared and initialized at the same time using


identifier = expression
Example:

Assignment Statement

Y=2;

checked scanf function call

assert ( scanf(%d, &Z ) == 1) ;

is used. Variables are used when they occur in any form of expression.

WARNING: Each variable must be individually initialized.

int X = 1 ;

For a program to be correct, every variable should receive a value BEFORE it

int xPosition = 25 , yPosition = 30

int M , N = 0

Explicit initialization in a declaration

Examples

/* only initializes N. */

T=X+3;
if ( Z ) ...

Good Style: All variables should be initialized with some value before they
are used in a program.
a

BAD Style: do not depend on the system to automatically initialize variables


for you. This is lazy and dangerous. Someday the variables will be initialized

As a matter of Good Technique: we ignore the default initialization of all variables to zero that

some C compilers do automatically. We think that relying on default initialization is a BAD HABIT that
should be avoided.

to RUBBISH and your program will CRASH.


a

identifierList is a comma separated list of identifiers


63

62

To check for use of uninitialized variables, examine every place in a program

When completing the statement you must account for all possible ways that

that a variable is used.

the use of the variable can be reached during program execution.

Do this systematically line by line, starting at the first line in the program.

You must also consider the possibility that a value might not be assigned to a
variable due to conditional statements or an unchecked scanf.

At EVERY place where a variable is used, complete the following statement


For EVERY possible way of reaching this use of the variable, the
variable MUST have a value BECAUSE ______________ .

int Y ;

int Z ;

...

...

...

if ( something )

for ( ... ; something ; ... )

X=1;

Y=2;

If you can not complete this statement, either

int X ;

scanf (%d &Z );

You dont understand the program




OR You have an uninitialized variable error at this point in the program.


If something is false then X and Y will not receive a value.

For a well structured program this statement should be really easy to

The unchecked scanf statement may not assign a value to Z a .

complete for almost all uses of variables.


Once a variable receives a value it is automatically not uninitialized.
a

This is why we suggest that every scanf statement must be checked to make sure it read values

into the expected number of variables.

64

65

Example of Uninitialized Variable Checking


main( )

Named Constants

b x

x2

/* Compute roots of equation a

0 */

double a, b, c ;

/* Coefficients */

double disc, discsq ;

/* Discriminant */

double x1, x2 ;

/* roots */

assert( scanf(%lg %lg %lg, &a, &b, &c ) == 3 );

A named constant is an identifier that serves as a synonym (name) for a


constant value.

printf(Coefficients are %g, %g, %g\n, a , b , c );

== 0.0 )
== 0.0 )

if ( a

Named constants are often used to provide a single point of definition for a

if ( b

printf(Equation has no roots \n);

constant value that is used throughout a program.

printf(One real root: %g\n, - c / b );

Using named constant makes programs more easily modifiable and easier to

else
else


understand.
discsq = b * b - 4.0 * a * c ;
if ( discsq

>= 0.0 )


Named constants makes program more readable, use mnemonic name for

disc = sqrt( discq ) ;


x1 = ( - b + disc ) / 2.0 * a ;

constant.

x2 = ( - b - disc ) / 2.0 * a ;
printf(Two real roots: %g and %g \n, x1 , x2 ) ;

Named constants makes program correctness easier to achieve.

else


Good Style: Avoid Magic Numbers

x1 = - b / ( 2.0 * a ) ;
x2 = sqrt( - discsq ) / ( 2.0 * a );
printf(Two complex roots: %g+%gI and %g-%gI \n, x1 , x2 , x1 , x2 );

Use named constants for all values that have any significant impact on the

programs operation.

67

66

Defining Named Constants


Named Types

Use the #define construct to create named constants


#define identifier expression
The identifier becomes a synonym for the expression in the rest of the
program. If the expression is a constant expression then the identifier can be
used anywhere that a constant can be used
Good Technique: ALWAYS enclose the expression in parentheses.

A named type is an type that has been associated with a specific identifier.
Named types are created using the typedef declaration.
Named types make program more easily modifiable, since there is a single
point of definition for the type.

Good Style: Use UPPER CASE names for defined constants to make them

If mnemonic names are used for the types, named types make programs

stand out in the program.

more readable.

Examples:

Named types make it easier to write a correct program.

#define CUBIC IN PER LB ( 166 )


#define SCALE FACTOR (5.0 / 9.0)
#define ARRAY SIZE ( 100 )

WARNING: common errors


#define N = 100
#define N 100 ;

Good Style: Avoid Magic Types


Use named types for all types that have any significant impact on the
programs operation.

/* WRONG, defines N to be = 100 */


/* WRONG, defines N to be 100 ; */
68

69

Reading Data and Printing in Ca

Typedef Declaration
A named type is created with the declaration

Input and Output are not part of the C language.

typedef type-name identifier ;

Builtin library functions are used for all reading and printing.

type-name can be any valid type including compound types or a new type

Put the construct

definition.

available.
The printf function does simple printing

typedef long int portableInt ;


typedef float realType ;

The scanf function is used to read values into variables.

portableInt I , J , A[ 100 ] ;
realType xAxis , yAxis , zAxis

stdio.h

at the start of every program to make the builtin input and output functions

Good Style: Use typedefs for all complicated types.


Examples:

#include

identifier becomes a new name for this type

The description of printf and scanf below is intended to get you started. Reading and Printing will

be discussed in more detail later in the course.

70

71

Format Strings

Conversion Specifier Characters


Conversion

A format string is used to specify how printf and scanf should operate.
For printf the format string specifes exactly how the printed output should look.
For scanf the format string specifes the exact form of the input that will be

Type

Specifier

int

%d or %i

char

%c

Strings

%s

double

%f or %e or %g printf

double

%lf or %le or %lg scanf

float

%f or %e or %g

short

%hd

long

%ld

read.
The format string consists of
conversion specifications a percent sign ( % ) followed by some optional
information, followed by a conversion specifier character that indicates the type of
data to be printed or read.
ordinary text Everything else. Printed as is by printf. Matched against the data
being read by scanfa
a

This feature is rarely used

Note that printf and scanf use different specifiers for double .
Use %% to print a %. Use \n to print a newline.
72

73

The printf Function


printf ( format-string

Printing Technique

, expressionList a ) ;

In a format string a constant between the % and the following control

The format-string controls how the information is printed.

character, specifies that the expression is to be printed using the number of


The expressions in the expressionList are printed in the order given.

characters specified by the constant. This feature can be used to print

The type of each expression must be compatible with the % item used in the

columns of values. Examples:

%10d

%16e

format-string
The printf prints to standard output.
By default each expression is printed using the minimum number of

If you are working at a terminal, this means printing to your screen.

characters required to express its value.

There are Unix/Windows commands that let you redirect standard out to a file.

All formatting and spacing must be provided by the programmer.


WARNING: make really sure that the type of the expression matches the type
of % character that you use to print it.
WARNING: make really sure that you have provided a % character for each
a

expression in the expression list.

An expressionList is a list of expressions separated by commas

75

74

The scanf Function


Examples Printing the Value of a Scalar Variable

int scanf ( format-string

, variable-address-list a ) ;

Examples:

The format-string controls how the information is read

int i , height , width ;


char c ;
float x ;
double y ;

Any ordinary text in the format string must match the input exactly.

scanf attempts to read values for each of the variables in the order given.
The type of each variable must be compatible with the % item used in the
format-string

printf("%d",
printf("%c",
printf("%f",
printf("%e",
printf("%g",

i)
c)
x)
x)
y)

;
;
; /* decimal form
*/
; /* scientific form
*/
; /* decimal or scientific form */

printf("height is %d and width is %d\n", height , width ) ;


printf("i = %8d, x = %14f\n", i, x) ;
printf("\n") ;
/* blank line */

76

scanf automatically skips white space between input values

A variable-address-list is a list of addresses of variables separated by commas

77

scanf returns the number of variables that it successfully read and stored.
Returns special value EOF if an error or end of input was detected.
Use the address-of operator

& to create the addresses of variables for the

arguments to scanf.
The address-of operator is almost always REQUIRED.

Examples - Reading Input


Examples:

int i , k ;
char c ;
double y ;

WARNING: forgetting the address of operator in a call to scanf will almost


certainly cause your program to CRASH.
Good Style: always check the value returned by scanf to make sure that you
read as many variables as you expected toa .
a

scanf("%d", &i) ;
/* read
scanf("%c", &c) ;
/* read
scanf("%lf", &y) ; /* read
scanf("%d%d", &i, &j ); /*

We may sometimes not do this check in these slides in order to keep the examples simple,

but it should always be done

78

79

one integer */
one character */
one double value */
read two integers */

Das könnte Ihnen auch gefallen