Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics Basic Program...

50
Fundamentals of C and C++ Programming

Transcript of Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics Basic Program...

Fundamentals of C and C++ Programming

EEL 3801 – Lotzi Bölöni

Sub-Topics

Basic Program StructureVariables - Types and DeclarationsBasic Program Control StructuresFunctions and their definitions Input/OutputBasic data StructuresMiscellaneous

EEL 3801 – Lotzi Bölöni

Basic Program Structure

The C Preprocessor–Header files–Macros

Global data declarationsFunction prototypesmain() function

–C/C++ statements

Definition of other functions

The preprocessor

EEL 3801 – Lotzi Bölöni

The C Preprocessor

Obeys special commands called preprocessor directives

Indicate certain things to be done to the program code prior to compilation. –Include certain other files when compiling–Replace some code by other code

Statements beginning with # are considered preprocessor directives

EEL 3801 – Lotzi Bölöni

Header Files

The #include directive tells the preprocessor to include the named files in the compilation process.

Allows the programmer to:–break up the program across several files for

modularity and reusability.–Include Standard C Library files that contain

“primitive” functions.

EEL 3801 – Lotzi Bölöni

Header Files (cont.)

The #include directive causes a copy of the designated file to be included in place of the directive.

Some important ones are: math.h stdio.h stdlib.h string.h

EEL 3801 – Lotzi Bölöni

Header Files (cont.)

The format of this directive is:

–#include “filename” - the preprocessor searches in the same directory as the file being compiled. Typically for user-defined files.–#include <filename> - the preprocessor

searches in pre-defined directories where the standard C Library files are located. Normally used for standard library files.

EEL 3801 – Lotzi Bölöni

The #define Directive

Symbol replacementCauses the preprocessor to physically replace in the source code prior to compilation, the symbol defined in the macro by the value assigned to that symbol, wherever that symbol is found in the source code.

#define PI 3.14159

EEL 3801 – Lotzi Bölöni

The #define Directive (cont.)

The macro replacementThe #define directive can also replace codeMacros may be defined either with or without arguments.

The replacement code text is put in place of the macro identifier.

Arguments should be between parentheses.

EEL 3801 – Lotzi Bölöni

The #define Directive (cont.)

Example:#define CIRCLE_AREA(x) ( PI * (x) * (x) )

When called:area = CIRCLE_AREA(4);

the preprocessor replaces CIRCLE_AREA with

( 3.14159 * (4) * (4) )

EEL 3801 – Lotzi Bölöni

The #define Directive (cont.)

It is important to use parentheses in the definition. Else, confusion to the compiler:

area = CIRCLE_AREA(c+2)

area = (3.14159 * (c+2) * (c+2) )

If no parentheses used, however,area = (3.14159 * c + 2 * c +2)

which is incorrect (product takes precedence)

EEL 3801 – Lotzi Bölöni

The #define Directive (cont.)

Scope of a macro or symbolic constant is:– until the end of the file–undefined with #undef

EEL 3801 – Lotzi Bölöni

Other Preprocessor Directives

#if …#endif: can force conditional compilation

#error: prints a message displayed as an error message - Page 527

# and ## operators: causes replacement text to be converted to a string - page 527

#line: causes subsequent source code lines to be renumbered from number

Elements of the C language

EEL 3801 – Lotzi Bölöni

Global Variable Declarations

Global variables should be defined outside of any function.

Can include simple variables such as characters, floating point, integers, or complex ones such as arrays, structures and unions.

Global type definitions should also be located in this part of the program.

EEL 3801 – Lotzi Bölöni

Function Prototypes

Tells the compiler:–type of data (if any) returned by function–number of parameters the function expects–the types of each parameter–the order in which the parameters are expected

Allows the compiler to validate function calls.

Required in C++ but not in C.

EEL 3801 – Lotzi Bölöni

Function Prototypes (cont.)

Permits coercion of arguments–Converts one type of data to another required by

the function

Example:

A function called max() will accept 3 integer arguments and return the largest one:

int max(int, int, int);

EEL 3801 – Lotzi Bölöni

main() Function

The main() function is part of every C and C++ program.

Every program in C/C++ begins by executing the main() function

No other function is necessary, but main() is.

A left brace { defines the beginning of its body, closed by a right brace }.

EEL 3801 – Lotzi Bölöni

C Statements

Composed of one or more machine level instructions.

Conclude with the semicolon ;Could be grouped together as a block of code by using the right and left brackets. { }

Example:

result = a + b + c * (d + e);

EEL 3801 – Lotzi Bölöni

User-Defined Functions

C programs typically require several functions besides main().–Some may be standard C library functions–Others may be user-defined functions

This is done to simplify the programming task by splitting various functionality between functions

Permits abstraction

Variables

EEL 3801 – Lotzi Bölöni

Variables

A variable is a memory location identified by a valid identifier.

An identifier is a series of digits, letters and underscores (_) but that does not begin with a digit.

Can be of any length, but only first 31 characters are recognized by ANSI C.

Case sensitive

EEL 3801 – Lotzi Bölöni

Variable Attributes

Name: the identifier of the memory location

Value: the value stored thereinType: the type of value to be stored therein

Storage ClassStorage durationScopeLinkage

EEL 3801 – Lotzi Bölöni

Variable Types

The variable can take on a value, which is stored in its memory location.

The size of the memory location depends on the type of value being stored. –character–integer–floating point–double precision floating point

EEL 3801 – Lotzi Bölöni

Integers

Typically 2 bytes long for 16-bit machines and 4 bytes long for 32-bit machines.

Can be signed or unsigned. Default is signed.

Can also be specified as short or long:–short => 2 bytes (16 bits long)–long => 4 bytes (32 bits long)

EEL 3801 – Lotzi Bölöni

Integers - Range

Bytes Signed Range Unsigned Range

1 -128 to 127 0 to 255

2 -32,768 to 32,767 0 to 65,535

4 -2,147,483,648 to 2,147,483,647

0 to 4,294,967,295

EEL 3801 – Lotzi Bölöni

Characters

Actually are integers but with secondary meaning.

Typically 1 byte long.Just long enough to fit the ASCII table of character representations.

Can be added just like integers, but one must be careful

EEL 3801 – Lotzi Bölöni

Floating Point

The basic data type for mathematical calculations

Designated as single precisionTypically 4 bytes long, allowing 7 significant digits and an exponent range of -37 to 38.

Example: 3.25e-02 = 3.25 x 10-2 = 0.0325

EEL 3801 – Lotzi Bölöni

Double Precision Floating Point

Adds more precision and range to the number represented.

Employs 8 bytes, allowing for 15 significant digits and a exponent range of -307 to 308

EEL 3801 – Lotzi Bölöni

Extended Precision Floating Pt.

Adds even more precision and range.Employs 10 bytes, 19 significant digits and a exponent range of -4931 to 4932

EEL 3801 – Lotzi Bölöni

Variable Type Declarations

All variables in C must be declared and typed.

This is typically done at the beginning of the program or of a function definition.

C++ allows variables to be declared and typed more flexibly, at the location where they are first used.

EEL 3801 – Lotzi Bölöni

Variable Type Declarations

Integers - basic declaration: int <variable name>;

Several variables can be declared in the same statement:

int <var1>, <var2>, … <varn>;

Values can be assigned during declaration:

int <var1> = 25;

EEL 3801 – Lotzi Bölöni

Variable Type Declarations

Other declarations for integers are:–unsigned int <var>;–unsigned long <var>;–unsigned short <var>;–long int <var>; (int can be omitted)–short int <var>; (int can be omitted)

int is signed by default.These are self-explanatory otherwise

EEL 3801 – Lotzi Bölöni

Variable Type Declarations

Floating point - basic declaration:

float <var>;Several variables can be declared in the same statement:

float <var1>, <var2>, … <varn>;

Values can be assigned during declaration:

float <var1> = 25.0;

EEL 3801 – Lotzi Bölöni

Variable Type Declaration

Double precision - basic declaration:

double <var>;Several variables can be declared in the same statement:

double <var1>, <var2>, … <varn>;

Values can be assigned during declaration:

double <var1> = 25.0;

EEL 3801 – Lotzi Bölöni

Variable Type Declaration

The character basic declaration is char <var>;

EEL 3801 – Lotzi Bölöni

Variable Type Definition

Very different from declaration.Allows the user to define an identifier to describe a new variable type.

The new variable type used in lieu of the other in declarations.

typedef

Example: typedef long unsigned int word;

EEL 3801 – Lotzi Bölöni

Determining Variable Size

The C unary operator sizeof returns the size of the variable or constant applied to.

The “argument” is a data type or constant.Returns the number of bytes required to store a value of a particular type.

Parentheses not required, but highly recommended.

Example: sizeof(int) returns 2.

EEL 3801 – Lotzi Bölöni

Storage Classes

Helps determine the variable’s storage duration, scope and linkage.

Two basic types:–automatic storage duration

auto register

–static storage duration extern static

EEL 3801 – Lotzi Bölöni

Automatic Storage Class

Automatic storage variables are –created when the block in which they are

declared is entered. –Exist while the block is active–destroyed when the block is exited

Only variables can have automatic storageA function’s local variables are automatic by default.

EEL 3801 – Lotzi Bölöni

Automatic Storage Class

Thus, auto keyword not used often.Can save memory because memory location is released for re-use when function exits.

Example of “principle of least privilege”: Why have something in storage when it is not needed?

EEL 3801 – Lotzi Bölöni

External Storage Class

External variables are global variables that exist as long as the program exists.

Variables declared at the top of the program file are by default external.

Variables declared inside blocks can also be declared external through the keyword extern prior to the declaration.

Example: extern int temperature;

EEL 3801 – Lotzi Bölöni

External Storage Class Linkage

The external variable is only good until the end of the file.

It can be extended to other files by declaring it again in other files, but the extern keyword in front of it must be used.

EEL 3801 – Lotzi Bölöni

Static Storage Class

Somewhere between global and automatic.

Can be only recognized within the block where it is declared.

But outlives the exiting of the function so it can retain its value when the function is called again.

EEL 3801 – Lotzi Bölöni

Scope Rules

The scope of an identifier is the portion of the program in which the identifier can be referenced.

The four scopes are:–function scope–file scope–block scope–function-prototype scope

EEL 3801 – Lotzi Bölöni

Scope Rules

Only “label identifiers” (colon after them) have function scope. Used to name the location in function.

Identifier declared outside of any function has file scope. Known in all functions after it is declared until the end of file.

global variables, function definitions function prototypes

EEL 3801 – Lotzi Bölöni

Scope Rules

Identifiers declared inside a block have block scope. Scope ends after }.–Static local variables have block scope. Storage

duration does not affect scope.–Local variables–function parameters

variables declared inside function prototype have function-prototype scope. Not recognized outside of prototype.

EEL 3801 – Lotzi Bölöni

Sample Program

/* Test Program #1 */

#include <stdio.h>

void a(void); /* function prototype */void b(void);void c(void);

int x=1; /* global variable */

main(){int x = 5; /* local to main() */{ int x = 7;} /* local to block within main()*/

a();b();c();a();b();c();return 0; }

EEL 3801 – Lotzi Bölöni

Sample Program (continued)

void a(void)

{

int x = 25;

x = x + 1;

.

}

void b(void)

{

static int x = 25;

x = x + 1

.

}

void c(void)

{

x = x * 10;

}