Академический Документы
Профессиональный Документы
Культура Документы
Introduction
FORTRAN
BASIC
Pascal
C
C++
Java
C#
Programming Language
Popularity
http://langpop.com/
10 Reasons to Learn C
http://iel.ucdavis.edu/publication/WhyC.htm
l
1.
History of C
C
Invented by Ritchie based on B, a simplified version of
BCPL.
Used to develop Unix operating system and Unix
commands.
Most system software such as OS are written in C or C++.
Replacement for assembly language for hardware
interface.
By late 1970's C had evolved to K & R C.
C Standards
1st C standard created in 1989 by ANSI, ratified by ISO in
1990.
It is called C89. Some call it C90.
2nd C standard was ratified in 1999, called C99.
Numerical extensions such as complex numbers, variable length
arrays, and IEEE floating-point arithmetic are major enhancement
in C99. C99 will be pointed out whenever features in C99 only are
presented.
Phases of Compilation-Based
Execution of a C Program
1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute
8
Phases of Compilation-Based
Execution of a C Program -Edit
This is accomplished with
an editor program.
Phases of Compilation-Based
Execution of a C Program -Preprocessing
10
Phases of Compilation-Based
Execution of a C Program -Preprocessing
These manipulations
usually consist of including other files in
the file to be compiled, performing various text replacements,
defining various macros, etc..
References:
In Deitel & Deitel, they are discussed in Chapter 13, p517.
Examples include:
#include <stdio.h>
#define <identifier>
<replacement text>
11
Phases of Compilation-Based
Execution of a C Program -Preprocessing
Phases of Compilation-Based
Execution of a C Program -Linking
A linker links the object code with the code for
the missing functions to produce an executable
image (with no missing pieces).
During linking, multiple object files might be
combined into one executable.
13
Phases of Compilation-Based
Execution of a C Program
Loading
and
Executing
The next phase is called loading.
15
16
17
A Simple C Program
/* File: hello.c
Print Hello, world on the screen */
#include <stdio.h>
int main()
{
printf(Hello, world\n");
return 0;
} // end function main()
18
A Simple C Program
/* File: hello.c
Print Hello, world on the screen */
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf(Hello, world\n");
system (pause);
return 0;
} // end function main()
19
/* File: hello.c
Print Hello, world on the screen */
#include <stdio.h>
int main()
{
printf(Hello, world\n");
return 0;
}
Comments
Text surrounded by /* and */ is ignored by
computer
Used to describe program
#include <stdio.h>
Preprocessing directive - tells computer to
load contents of a header file
<stdio.h> allows standard input/output
20
/* File: hello.c
Print Hello, world on the screen */
#include <stdio.h>
int main()
{
printf(Hello, world\n");
return 0;
}
int main()
C programs contain one or more functions,
exactly one of which must be main
Parenthesis used to indicate a function
int means that main "returns" an integer
value
Braces indicate a block
The bodies of all functions must be
contained in braces
We will enforce this style with braces.
21
/* File: hello.c
Print Hello, world on the screen */
#include <stdio.h>
int main()
{
printf(Hello, world\n");
return 0;
}
22
/* File: hello.c
Print Hello, world on the screen */
#include <stdio.h>
int main()
{
printf(Hello, world\n");
return 0;
}
return 0;
A way to exit a function.
return 0, in this case, means that the program
terminated normally.
The returned value of 0 is displayed in the exit status
in ChIDE.
Right brace }
Indicates end of main has been reached.
23
Structure of a C Program
24
Preprocessor
Directives
Global
Declarations
variables
function prototypes
int main ()
{
Local declarations
Statements
}
Other functions...
void xxx()
{
}
void xxx()
{
}
25
Preprocessor
Directives
Global
Declarations
variables
Other functions...
void xxx()
{
}
void xxx()
{
}
int main ()
{
Local declarations
Statements
}
26
27
28
Data Types in C
Unlike Java, C contains only four standard data types: void,
char, integer types, and floating point types.
As we will see, the size of these data types is machine and system
dependent.
Since we sometimes need to know the size of a data type at
runtime, C provides an operator, sizeof(), that will return the
size of any data type in bytes.
Example:
/* x will contain 4 on most systems */
int x = sizeof (int);
30
Data Types in C
Unlike Java, C contains only four standard data types: void,
char, integer types, and floating point types.
void: When used as a return value from a function, indicates
that nothing is returned.
char:
Usually a single byte.
Usually represents a value from the ASCII table.
Can also be interpreted as a small signed integer (between -128 and
127).
Declared using the char keyword.
Character literals always in single quotes.
31
ASCII Table
32
Data Types in C
int: Integer data type. Comes in different flavors,
depending on the modifiers (short or long, signed or
unsigned):
33
Data Types in C
int:
34
Data Types in C
float: Floating point data type.
Comes in three sizes: float, double, long double.
36
INT_MAX
SHRT_MAX
CHAR_MAX
UINT_MAX
USHRT_MAX
UCHAR_MAX
FLT_MAX
DBL_MAX
38
Valid Identifiers
Notes:
The first character must not be a digit.
In the ANSI C standard, an identifier can be of any length, but the
compiler will only look at the first 31 characters.
An identifier cannot duplicate a reserved word.
Further Notes:
Note that, in contrast to Java, $ is not a valid character in a C
identifier.
Like Java and C++, C is case sensitive.
Use of leading underscores is discouraged for general use.
39
Variable Declarations
Variables are named locations in memory that contain
a value.
Variable declarations are made in C just like in Java.
<data type> <variable name>;
int
numOfStudents;
float numHoursWorked;
Variable Declarations
Some good rules for variable names:
Use either capitalization or underscores to create multi-word
identifiers.
Abbreviations should be long enough to clearly indicate what is
being abbreviated.
Avoid the use of generic names.
Dont create several variable names that differ only by one or
two characters.
41
Data Types in C
Differences with Java
Note that there is no boolean data type in C.
Boolean evaluations are done through integers (a 0 represents false, a
non-zero value represents true).
C has pointers!! This is not a data type per se, but can be
applied to any data type, even ones that we create.
This is a complex subject that we will discuss in more detail shortly.
42
Constants
Constants are values that cannot be changed during
the execution of a program.
Well consider three types of constants:
literals
#define preprocessor directives
Use of the const declaration on a variable.
43
Literals
As we know, a variable is a named storage location in
the computers memory.
A literal, on the other hand, is a constant value that is
hard coded into the program.
It is not associated with a named location in memory.
The value does not change.
Literals
Integer literals are numbers without decimal values.
5, 236, -7
int x = 5;
45
Literals
Integer literals are numbers without decimal values.
5, 236, -7
int x = 5;
46
Literals
String literals are character strings in double quotes.
Hello World
h
Literals
String Declarations
Strings can be declared with statements like the following:
char str[] = Hello;
char *str = Hello;
With declarations like this, C creates a character array as
follows:
H E
O \0
str
The variable str is a char* that points to the first element in the array.
The \0 is automatically appended in a declaration.
Preprocessor Constants
#define
#define constants are macros that replace the
<identifier> with the text that follows:
Model:
Exam:
49
Preprocessor Constants
#define
The header file <math.h> contains many predefined
constants that we can use (e.g., M_PI, M_E, ...).
However, to use them in Visual C++, we must include
the following preprocessor directive in our files
before we include <math.h>:
#define _USE_MATH_DEFINES
50
Variable Constants
The final way of declaring a constant is by declaring a variable
constant:
Notes:
The modifier const comes before the data type.
The variable must be initialized to be used effectively. If not, its value
will be whatever is in memory when the declaration is executed.
Note: this is different from C++, which requires const variables to be
initialized when they are declared. In C, no compile error if not initialized.
52
Format-control-string:
Always enclosed in double quotation marks.
Uses format specifications to describe output format. Each specification begins with
a percent sign (%) and ends with a conversion specifier.
Escape sequences can also be embedded in the format string.
arguments
are matched with the conversion specifiers in the format-control-string in both type
and number. The matching is done left-to-right.
53
Conversion code
There are about 30 of these, but we are only concerned with a few.
See chart next page.
54
char
%c
%d
%u
octal number
%o
hexadecimal number
%x, %X
float
%f
double
%f or %lf
string
%s
pointer
%p
55
Data Type
%c
Char
%s
String
%d
Signed Integer
%u
Unsigned integer
%f
Float
%lf
Double
%Lf
Long Double
%p
Pointer value
%x, %X
Hexadecimal value
(letters)
%o
Octal Value
%e, %E
Scientific notation
56
<Size>
57
<min width>
Used to specify the minimum number of positions in the output. (Very useful when
printing in columns.)
Default is right justified within the field specified (use minus sign flag to left justify).
printf() will override the width specified if the output is larger.
int x = 25;
25
25
00025
58
<.precision>
25.356701
25.36
25.36
59
<flag>
+25
25
000000025
60
61
62
63
65
66
67
68
70
72
74
77
79
81
85
Conversion Specifiers
printf() and scanf()
87
Data Types in C
Pointers
Pointers are variables whose values are memory
addresses (Deitel, 277).
Normally, a variable directly contains a specific value.
A pointer, on the other hand, contains an address of a variable
that contains a specific value.
88
Data Types in C
Pointers
Pointers, like all variables, must be defined before they can
be used.
We define a pointer by using an asterisk before the variable
name. Thus, the definition:
int *countPtr, count;
Data Types in C
Pointers
Pointers are variables whose values are memory
addresses.
int count;
int *countPtr = &count:
90
Data Types in C
Pointers
The &, or address operator, is a unary operator that returns
the address of its operand.
For example, assuming the definitions
int y = 5;
int *yPtr;
the statement
yPtr = &y;
Data Types in C
Pointers
Again, assuming the definitions
int y = 5;
int *yPtr;
the statement
yPtr = &y;
92
Data Types in C
Pointers
Lets assume that the integer variable y is stored at
location 600000, and the pointer variable yPtr is
stored at location 500000.
Then the result of the statement:
yPtr = &y;
is:
93
Data Types in C
Pointers
When the unary * operator, commonly referred to as
the indirection operator or dereferencing operator, is
applied to a variable outside of a declaration, it
returns the value of the object to which its operand
(i.e., a pointer) points.
For example, the statement
printf( "%d", *yPtr );
prints the value of variable y, namely 5.
Using * in this manner is called dereferencing a
pointer.
94
Data Types in C
Pointers
The next figure demonstrates the pointer operators & and *.
The printf conversion specifier %p outputs the memory
location as a hexadecimal integer on most platforms.
Notice that the address of a and the value of aPtr are
identical in the output, thus confirming that the address of a
is indeed assigned to the pointer variable aPtr (line 11).
The & and * operators are complements of one another
when theyre both applied consecutively to aPtr in either
order (line 21), the same result is printed.
95
96
Data Types in C
Pointers
97
98
Data Types in C
Pointers -- Summary
Pointers are declared using the asterisk (*) in a
declaration:
int *xPtr;
float *fltPtr;