Beruflich Dokumente
Kultur Dokumente
C Programming
C Programming
C Programming
B Language
In 1969, Thompson (researcher at Bell Labs)
created the language B by simplifying the
research language Basic Combined
Programming Language (BCPL) so its
interpreter would fit in the PDP-7's 8K word
memory
the hardware memory limits only provided
room for an interpreter, not a compiler. The
resulting slow performance prevented B from
being used for systems programming of
UNIX itself.
C Programming
Shortcomings of B Language
B also retained the typelessness of BCPL;
the only operand was a machine word
New computer PDP-11 featured hardware
support for data types of several different
sizes, and the B language had no way to
express this
Performance was also a problem, leading
Thompson to reimplement the UNIX OS in
PDP-11 assembler rather than B
C Programming
Language New B
Dennis Ritchie capitalized on the more
powerful PDP-11 to create "New B," which
solved both problems, multiple data types,
and performance. "New B"the name
quickly evolved to "C"was compiled rather
than interpreted, and it introduced a type
system, with each variable described in
advance of its use
C Programming
BCPL->B->New B->C
The initial development of C occurred at
AT&T Bell Labs between 1969 and 1973;
according to Ritchie, the most creative period
occurred in 1972. At that year a great part of
Unix was rewritten in C.
By 1973, with the addition of struct types, the
C language had become powerful enough
that most of the Unix kernel was in C. The
new language was named "C" because its
features were derived from "B
Unix was one of the first operating system
kernels implemented in a language other
C Programming
than assembly.
C Standardization
K & R C in
1978
ANSI C/C89
ISO C/C90
ISO/IEC
9899:1999/C99
C Programming
C/C++ Applications
Operating Systems:
UNIX, Windows 95, 98, 2000, XP, Apple OS X,
Symbian OS
Language Compilers:
Portable C Compiler (PCC)
Simulators
GEMS, gem5
Applications:
Adobe Systems, MySQL, Winamp Media Player,
Mozilla Firefox browser
Embedded Systems
Microcontroller programming
C Programming
C Programming
C Programming
Strengths
Efficiency. Efficiency has been one of C's
advantages from the beginning. Because C was
intended for applications where assembly
language had traditionally been used. It was
crucial that C programs could run quickly and in
limited amounts of memory.
Portability. Although program portability wasn' t a
primary goal of C, it has turned out to be one of
the language's strengths. When a program must
run on computers ranging from PCs to
supercomputers, it is often written in C. Another is
that C compilers are small and easily written.
which has helped make them widely available.
C Programming
Strengths
Power. C's large collection of data types and
operators help make it a powerful language. In C,
it's often possible to accomplish quite a bit with
just a few lines of code.
Flexibility. Although C was originally designed for systems
programming, it has no inherent restrictions that limit it to
this arena. C is now used for appIications of all kinds, from
embedded systems to commercial data processing.
Moreover, C imposes very few restrictions on the use of its
features; operations that would be illegal in other languages
are often permitted in C. For example, C allows a character
to be added to an integer/ floating value. This flexibility can
make programming easier, although it may allow some bugs
to slip through.
C Programming
Strengths
Standard library. One of C's greal strengths is its
standard library, which contains hundreds of
functions for input/output, string handling, storage
allocation, and other useful operations.
Integration with UNIX. C is particularly powerful in
combination with UNIX (including the popular
variant known as Linux). In fact, some UNIX tools
assume that the user knows C.
C Programming
Weaknesses
C's weaknesses arise from the same source
as many of its strengths: C's closeness to the
machine. Here are a few of C's most
notorious problems:
C programs can be error-prone: In this respect, C
is a lot like assembly language, where most errors
aren't detected until the program is run. we' ll see
how an extra semicolon can create an infinite loop
or a missing & symbol can cause a program
crash.
C Programming
Weaknesses
C programs can be difficult to understand: C's
terse nature make programs hard to understand.
C was designed at a time when interactive
communication with computers was tedious at
best. As a result, C was purposefully kept terse to
minimize the time required to enter and edit
programs. C's flexibility can also be a negative
factor; programmers who are too clever for their
own good can make programs almost impossible
to understand.
C Programming
Weaknesses
C programs can be difficult to modify. Large
programs written in C can be hard to change if
they haven't been designed with maintenance in
mind. Modern programming languages usually
provide features such as classes and packages
that support the division of a large program into
more manageable pieces. C. unfortunately. lacks
such features.
C Programming
Preprocessor
Compiler
Library
or
other
files
Object
code
Linker
Executabl
e code
C Programming
Source Code
C Programming
C Programming
Running
C Programming
Size signed
(B)
unsigned
char
short
int
1
2
4
128 to +127
32,768 to +32,767
2,147,483,648 to
+2,147,483,647
0 to 255
0 to 65,535
0 to
4,294,967,29
5
long
9,223,372,036,854,775,80
8 to
+9,223,372,036,854,775,
807
0 to
18,446,744,0
73,709,551,6
15
C Programming
C Programming
C Programming
limits.hinteger ranges
char
SCHAR_MIN, SCHAR_MAX, UCHAR_MAX
short
SHRT_MIN, SHRT_MAX, USHRT_MAX
int
INT_MIN, INT_MAX, UINT_MAX
long
LONG_MIN, LONG_MAX, ULONG_MAX
C Programming
C Programming
double
Size(bytes signed
)
4
3.4E +/- 38
8
C Programming
C Programming
Variable
Variable is a named location in a computers
memory
0
1
2
3
.
.
.
4G-1
C Programming
R
A
M
Variable name
Letters(a-z, A-Z), Digits(0-9), underscore(_)
First character must be a letter
Don't begin variable names with underscore,
but you can.
C language is case sensitive. So Upper and
lower case letters are distinct
Traditional C practice is to use lower case for
variable names
No keyword as variable name
variable name should describe the purpose
of it.
C Programming
Variable name
Examples:
number1
1number //illegal
_1number //ok
_result_12
long //illegal
total values//illegal
C Programming
printf
/*printf() usage
int printf ( const char * form, ... );
format: %[flags][width][.precision]
[length]specifier*/
#include <stdio.h>
int main(){
char c=A;
short s=12345;
int i=23;
long l=12121;
printf(c=%c, s=%d, i=%d, l=%ld\n,c,s,I,l);//d or i
printf(c=%d, s=%d, i=%d, l=%ld\n,c,s,I,l);//%c
replaced with %d
printf(c=%hhd, s=%hd, i=%d, l=%ld\n,c,s,I,l);//hhd,hd
return 0;
}
C Programming
printf
/*Breaking string in the printf() to multiple
lines*/
#include <stdio.h>
int main(){
printf(hello world\n);
printf(hello world
);//wrong
//one sol
printf("hello ");
printf("world");
printf("\n");
//or
printf("hello \
"world\n");
C Programming
scanf function
int scanf ( const char * format, ... );
Read formatted data from stdin
Reads data from stdin and stores them
according to the parameter format into the
locations pointed by the additional
arguments.
The additional arguments should point to
already allocated objects of the type
specified by their corresponding format
specifier within the format string.
C Programming
scanf parameters
format: C string that contains a sequence of
characters that control how characters
extracted from the stream are treated:
Whitespace character: the function will read and
ignore any whitespace characters encountered
before the next non-whitespace character
(whitespace characters include spaces, newline
and tab characters -- see isspace). A single
whitespace in the format string validates any
quantity of whitespace characters extracted from
the stream (including none).
scanf( %d,&number1); scanf( %d %d
,&num1,&num2);
C Programming
scanf parameters
Non-whitespace character, except format specifier
(%): Any character that is not either a whitespace
character (blank, newline or tab) or part of a format
specifier (which begin with a %character) causes the
function to read the next character from the stream,
compare it to this non-whitespace character and if it
matches, it is discarded and the function continues
with the next character of format. If the character
does not match, the function fails, returning and
leaving subsequent characters of the stream unread.
scanf( %d, %d ,&num1,&num2);
scanf( %d , %d,&num1,&num2);//different
C Programming
scanf parameters
Format specifiers: A sequence formed by an
initial percentage sign (%) indicates a format
specifier, which is used to specify the type
and format of the data to be retrieved from
the stream and stored into the locations
pointed by the additional arguments
scanf( %d\n,&num1);
C Programming
Arithmetic Operators
Operator
Meaning
Examples
Addition
x=3+2;
z=x+y;
Subtraction
x=3-2;
z=x-y;
Multiplication
x=3*2; z=x*y*23;
Division
x=3/2;
z=x/y;
Remainder
x=5%2;
z=x%y
C Programming
Relational Operators
Used for comparison
result is either 1(true) or 0 (false)
< less than
<= less than or equal to
> greater than
>= greater than or equal to
C Programming
Equality Operators
test if numbers are equal or not
result is either 1(true) or 0 (false)
== equal
!= not equal
C Programming
Logical Operator
&& true (1) if both values are non-zero
|| true (1) if both either value is non-zero
&& and || evaluated left to right, and
evaluation stops as soon as the truth or
falsehood of the result is known
! converts non-zero value to false (0) and
zero value to true(1)
The precedence of && is higher than that of
||, and both are lower than relational and
equality operators
C Programming
C Programming
C Programming
C Programming
Bit-wise Operators
only applied to integral operands, that is,
char, short, int, and long, whether signed or
unsigned
& bitwise AND
| bitwise inclusive OR
^ bitwise exclusive OR
<< left shift
>> right shift
~ one's complement (unary)
C Programming
Bit-wise Operators
The bitwise AND operator & is often used to
mask off some set of bits
n = n & 0177; //sets to zero all but the low-order 7
bits of n.
Bit-wise Operators
&& and & are not same. if x is 1 and y is 2,
then x & y is zero while x && y is one.
The shift operators << and >> perform left
and right shifts of their left operand by the
number of bit positions given by the right
operand, which must be non-negative.
Thus x << 2 shifts the value of x by two positions,
filling vacated bits with zero; this is equivalent to
multiplication by 4.
Bit-wise Operators
Right shifting a signed quantity will fill with bit
signs (``arithmetic shift'') on some machines
and with 0-bits (``logical shift'') on others.
The unary operator ~ yields the one's
complement of an integer; that is, it converts
each 1-bit into a 0-bit and vice versa.
x = x & ~077 better than x & 0177700 sets the
last six bits of x to zero.
C Programming
Bit-wise Operators
Note that x & ~077 is independent of word length,
and is thus preferable to, for example, x &
0177700, which assumes that x is a 16-bit
quantity. The portable form involves no extra cost,
since ~077 is a constant expression that can be
evaluated at compile time.
C Programming
C Programming
Conditional Expressions
expr1 ? expr2 : expr3
the expression expr1 is evaluated first. If it is nonzero (true), then the expression expr2 is
evaluated, and that is the value of the conditional
expression. Otherwise expr3 is evaluated, and
that is the value. Only one of expr2 and expr3 is
evaluated
z = (a > b) ? a : b; /* z = max(a, b) */
if f is a float and n an int, then the expression (n >
0) ? f : n is of type float regardless of whether n is
positive.
C Programming
Conditional Expressions
for (i = 0; i < n; i++)
printf("%6d%c", a[i], (i%10==9 || i==n-1) ?
'\n' : ' ');
A newline is printed after every tenth element, and
after the n-th. All other elements are followed by
one blank
C Programming
Constants
Character constants: a
char c=A;
Integer constants:
34565 signed int
123u or 123U unsgined int
23232L or 23232l signed long
121234UL unsigned long
can be written in octal(0) and hexadecimal (0X or
0x) format
C Programming
Constants
String: a sequence of zero or more
characters surrounded by double quotes
My name is abid
My name is Arif, studying IIU.\
C Programming
Escape sequences
sequences look like two characters, but
represent only one:
\a alert (bell) character
\b backspace
\f form feed
\n newline or line feed
\r carriage return
\t horizontal tab
\v vertical tab
\\backslash
C Programming
Escape sequences
\?question mark
\' single quote
\" double quote
\ooo octal number --\xhh hexadecimal number ---leading x
'\0' represents the character with value zero, the
null character
C Programming
C Programming
constant
The qualifier const can be applied to the
declaration of any variable to specify that its
value will not be changed
const int decimal_base=10;
C Programming
Type Conversion
automatic conversions:
convert a ``narrower'' operand into a ``wider'' one
without losing information, such as converting an
integer i into floating point in an expression like f +
i.
C Programming
Type Conversion
If there are no unsigned operands, then
following conversion rules apply:
If either operand is long double, convert the other
to long double.
Otherwise, if either operand is double, convert the
other to double.
Otherwise, if either operand is float, convert the
other to float.
Otherwise, if either operand is long, convert the
other to long.
Otherwise, convert char and short to int.
C Programming
Type Conversion
Conversion on assignment:
the value of the right side is converted to the type
of the left, which is the type of the result.
C Programming
Type Conversion
Forced Conversion:
(Type name) expression
int i; float f; int res= i+(int)f;
C Programming
Evaluation Order
Operands Evaluation:
C, like most languages, does not specify the order
in which the operands of an operator are
evaluated. (The exceptions are &&, ||, ?:, and `,'.)
For example, in a statement like x = f() + g();
f may be evaluated before g or vice versa; thus if
either f or g alters a variable on which the other
depends, x can depend on the order of
evaluation.
Intermediate results can be stored in temporary
variables to ensure a particular sequence.
f=f();g=g();x=f+g;
C Programming
Evaluation Order
Arguments evaluation:
Similarly, the order in which function arguments
are evaluated is not specified, so the Statement
printf("%d %d\n", ++n, power(2, n)); /* WRONG */
can produce different results with different
compilers, depending on whether n is
incremented before power is called.
Solution, of course, is to write ++n; printf("%d
%d\n", n, power(2, n));
C Programming
Evaluation Order
Be careful when using Function calls, nested
assignment statements, and increment and
decrement operators in an expression
Moral lesson: Dont write code that depends
on order of evaluation
C Programming
C Programming
Main()
int main(void);//OK
int main();//DONT USE
int main(int argc, char **argv); //OK
int main(int argc, char *argv[]); //OK
C Programming