CHAPTER 1 C Programing

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

CHAPTER 1 : INTRODUCTION TO C PROGRAMMING

I- Programming and Pogramming Languages


The native language of a computer is binary—ones and zeros—and all instructions
and data must be provided to it in this form. Native binary code is c alled machine
language. The earliest digital electronic computers were programmed directly in
binary, typically via punched cards, plug-boards,
or front-panel switches. Later, with the advent of terminals with keyboards and
monitors, such
programs were written as sequences of hexadecimal numbers, where each
hexadecimal digit represents a four binary digit sequence. Developing correct
programs in machine language is tedious and complex, and practical only for very
small programs.
In order to express operations more abstractly, assembly languages were
developed. These languages have simple mnemonic instructions that directly map
to a sequence of machine language operations. For example, the MOV instruction
moves data into a register, the ADD instruction adds the contents of two registers
together. Programs written in assembly language are translated to machine code
using an assembler program. While assembly languages are a considerable
improvement on raw binary, they still very low-level and unsuited to large-scale
programming. Furthermore, since each processor provides its own assembler
dialect, assembly language programs tend to be non-portable; a program must be
rewritten to run on a different machine. The 1950s and 60s saw the introduction of
high-level languages, such as Fortran and Algol.
These languages provide mechanisms, such as subroutines and conditional looping
constructs, which greatly enhance the structure of a program, making it easier to
express the progression of instruction
execution; that is, easier to visualise program flow. Also, these mechanisms are an
abstraction of the underlying machine instructions and, unlike assembler, are not
tied to any particular hardware.
Thus, ideally, a program written in a high-level language may be ported to a
different machine and
II- Writing Your C Program
Source code of the C program is written in text files
Header files usually with the suffix .h
Sources files usually named with the suffix .c
Header and source files together with declaration and definition
(of functions) support
Organization of sources into several files (modules) and libraries
Modularity – Header file declares a visible interface to others
A description (list) of functions and their arguments without particular
implementation
Reusability

LEVEL I COURSE OF STRUCTURED PROGRAMING ISLAPE BY TAGA


Only the “interface” declared in the header files is need to use
functions from available b inary libraries
II.1 Writing Codes in C
Each executable program must have at least one function and the
function has to b e main()
The run of the program starts at the beginning of the function
main(), e.g.,
#include <stdio.h>
int main(void)
{
printf("I like BE5B99CPL!\n");
return 0;
}
The form of the main() function is prescribed
Source files are compiled by the compiler to the so-called object
files usually with the suffix .o
Object code contains relative addresses and function calls or just references to
function without known implementations.
The final executable program is created from the object files by
the linker
II.2 Structure of c source code
Commented source file program.c
/* Comment is inside the markers (two characters)
and it can be split to multiple lines */
// In C99 - you can use single line comment
#include <stdio.h> /* The #include direct causes to
include header file stdio.h from the C standard
library */
int main(void) // simplified declaration
{ // of the main function
printf("I like BE5B99CPL!\n"); /* calling printf()
function from the stdio. h library to print string
to the standard output. \n denotes a new line */
return 0; /* termination of the function. Return
value 0 to the operating system */
}

II.3 Program Building: Compiling and Linking


The previous example combines three steps of building the program
into a single call of the command (clang or gcc). The particular
steps can be performed individually
1. Text preprocessing by the preprocessor, which utilizes its own
macro language (commands with the prefix #)
All referenced header files are included into a single source file

LEVEL I COURSE OF STRUCTURED PROGRAMING ISLAPE BY TAGA


A) Compilation of the source file into the object file
Names of the object files usually have the suffix .o
clang -c program.c -o program.o

The command combines prepro cessor and compiler.


3. Executable file is linked from the particular object files and
referenced libraries by the linker (linking), e.g.,
clang program.o -o program

B) Compilation and Linking Programs


Program development is editing of the source co de (files with suffixes .c and .h); Human
readable
Compilation of the particular source files (.c) into object files (.o or
.obj) ; Machine readable
Linking the compiled files into executable binary file;
Execution and debugging of the application and rep eated editing of
the source co de.

C) Steps of Compiling and Linking


Preprocessor – allows to define macros and adjust compilation
according to the particular compilation environment
The output is text (“source”) file.
Compiler – Translates source (text) file into machine readable form
Native (machine) co de of the platform, byteco de, or assembler alternatively
Linker – links the final application from the object files
Under OS, it can still reference library functions (dynamic libraries linked
during the prog ram execution), it can also contains OS calls (libraries).
Particular steps preprocessor, compiler, and linker are usually
implemented by a “single” program that is called with appropriate
arguments.
II.4 COMPILERS OF C PROGRAM LANGUAGE
In CPL, we mostly use compilers from the families of compilers:
gcc – GNU Compiler Collection
https://gcc.gnu.org
clang – C language family frontend for LLVM

LEVEL I COURSE OF STRUCTURED PROGRAMING ISLAPE BY TAGA


http://clang.llvm.org
Under Win, two derived environments can b e utilized: cygwin https://www.cygwin.com/ or
MinGW http://www.mingw.org/
Basic usage (flags and arguments) are identical for b oth compilers
clang is compatible with gcc
Example
compile: gcc -c main.c -o main.o
link: gcc main.o -o main

III- Identifiers
Identifiers (i.e., variable names, function names, etc) are made up of letters and
digits, and are
case-sensitive. The first character of an identifier must be a letter, which includes
underscore (_). The C language has 32 keywords which are reserved and may not
be used as identifiers (eg, int,while, etc). Furthermore, it is a good idea to avoid
redefining identifiers used by the C standard library (such as standard function
names, etc).
Style Note. Use lowercase for variable names and uppercase for symbolic
constants.
Local variable names should be short and external names should be longer and more
descriptive. Variable names
can begin with an underscore (_), but this should be avoided as such names, by convention,
are reserved for library implementations.
IV- Types
C is a typed language. Each variable is given a specific type which defines what values it can
represent, how its data is stored in memory, and what operations can be performed on it. By
forcing the programmer to explicitly define a type for all variables and interfaces, the type
system enables
the compiler to catch type-mismatch errors, thereby preventing a significant source of bugs.
There are three basic types in the C language: characters, and integer and floating-point
-integer: int x;
- character: char x;
floating point (approximate representation for real numbers): float x
The numerical types come in several of sizes. Table 2.1 shows a list of C types and their
typical

LEVEL I COURSE OF STRUCTURED PROGRAMING ISLAPE BY TAGA


TABLE 2.1: C DATA TYPES AND THEIR USUAL SIZES.

Note. The size of a type in number of characters (which is usually equivalent to number of
bytes)
can be found using the sizeof operator. This operator is not a function, although it often
appears
like one, but a keyword. It returns an unsigned integer of type size_t, which is defined in
header-file
stddef.h.

The keywords short and long are known as type qualifiers because they affect the size of a
basic
int type. (The qualifier long may also be applied to type double.) Note, short and long, when
used on their own as in
short a;
long x;
are equivalent to writing short int and long int, respectively
Other type qualifiers are signed,
unsigned, const, and volatile. The qualifiers signed or unsigned can apply to char or any
integer type. A signed type may represent negative values; the most-significant-bit (MSB) of
the
number is its sign-bit, and the value is typically encoded in 2’s-complement binary.
Note. Integer types are signed by default (e.g., writing short is equivalent to writing signed
short int). However, whether plain char’s are signed or unsigned by default is machine dependent.

The qualifier const means that the variable to which it refers cannot be changed.
const int DoesNotChange = 5;
DoesNotChange = 6; /* Error: will not compile */
The qualifier volatile refe
rs to variables whose value may change in a manner beyond the normal
control of the program. This is useful for, say, multi-threaded programming or interfacing to
hardware; topics which are beyond the scope of this text. The volatile qualifier is not directly
relevant
to standard-conforming C programs, and so will not be addressed further in this text.

LEVEL I COURSE OF STRUCTURED PROGRAMING ISLAPE BY TAGA


Finally, there is a type called void, which specifies a “no value” type. It is used as an
argument
for functions that have no arguments, and as a return type for functions that return no value

IV- Constants
Constants can have different types and representations. This section presents
various constant types
by example. First, an integer constant 1234 is of type int. An constant of type long
int is suffixed by an L, 1234L; (integer constants too big for int are implicitly
taken as long). An unsigned int is suffixed by a U, 1234U, and UL specifies
unsigned long.
Integer constants may also be specified by octal (base 8) or hexadecimal (base 16)
values, rather than decimal (base 10). Octal numbers are preceded by a 0 and hex
by 0x. Thus, 1234 in decimal is equivalent to 02322 and 0x4D2. It is important to
remember that these three constants represent exactly the same value (0101 1101
0010 in binary). For example, the following code

#include <stdio.h>
#include <stdlib.h>

int main ( void)


{

int x = 1234, y = 02322, z = 0x4D2;


// conversion of x to base 8 and 16
printf("%d\t%o\t%x\n", x, x, x);
// conversion of y and z to base 10
printf("%d\t%d\t%d\n", x, y, z);
}
Symbolic Constants
Symbolic constants represent constant values, from the set of constant types mentioned above,
by a symbolic name. For example,
#define BLOCK_SIZE 100
#define TRACK_SIZE (16*BLOCK_SIZE)
#define HELLO "Hello World\n"
#define EXP 2.7183
Wherever a symbolic constant appears in the code, it is equivalent to direct text-replacement

LEVEL I COURSE OF STRUCTURED PROGRAMING ISLAPE BY TAGA


with
the constant it defines. For example,
printf(HELLO);

Note. The #define symbol, like the #include symbol for file inclusion, is a preprocessor
command
(see Section 10.2). As such, it is subject to different rules than the core C language.
Importantly,
the # must be the first character on a line; it must not be indented.
Another form of symbolic constant is an enumeration, which is a list of constant integer
values.
For example,
enum Boolean { FALSE, TRUE };
The enumeration tag Boolean defines the “type” of the enumeration list, such that a variable
may
be declared of the particular type.
enum Boolean x = FALSE;
If an enumeration list is defined without an explicit tag, it assumes the type int. 4 For
example,
enum { RED=2, GREEN, BLUE, YELLOW=4, BLACK };
int y = BLUE;
The value of enumeration lists starts from zero by default, and increments by one for each subsequent
member (e.g., FALSE is 0 and TRUE is 1). List members can also be given explicit integer values,
and non-specified members are each one greater than the previous member (e.g., RED is 2, GREEN
is 3, BLUE is 4, YELLOW is 4, and BLACK is 5).

V- printf Conversion Specifiers


The standard function printf() facilitates formatted text output. It merges numerical
values of
any type into a character string using various formatting operators and conversion
specifiers.

printf("Character values %c %c %c\n", ’a’, ’b’, ’c’);


printf("Some floating-point values %f %f %f\n", 3.556, 2e3, 40.1f);
printf("Scientific notation %e %e %e\n", 3.556, 2e3, 40.1f);

LEVEL I COURSE OF STRUCTURED PROGRAMING ISLAPE BY TAGA


printf("%15.10s\n", "Hello World\n"); /* Right-justify string with space for
15 chars, print only first 10 letters */
printf() and padding
The width is a number which tells printf how many spaces to add to
the output in order for the result to have the specifid characters.
#include <stdio.h>
#include <stdlib.h>
int main() {
int a = 100;
int b = 1000;
int c = 10000;
printf("%7d\n", a);
printf("%7d\n", b);
printf("%7d\n", c);
printf("%7d\n", 1000000);
}
prints
100
1000
10000
1000000

V.1 printf() and precision


Precision has diffrent meaning based on each type:
▶ for integers it denotes the least amount of digits to be printed
(possible by including additional zeros a the beginning)
▶ for flats is represents the number of digits after the decimal
▶ for strings it denotes the maximum number of characters to be
printed

V.2 int and precision


Denotes the least amount of digits to be printed (possible by including
additional zeros a the beginning)
#include <stdio.h>
#include <stdlib.h>
int main() {
int a = 100;
int b = 10000;
int c = 1000000;
printf( "%10.7d\n", a );
printf( "%.7d\n", b );
printf( "%.7d\n", c );
return 0;
}
prints
0000100

LEVEL I COURSE OF STRUCTURED PROGRAMING ISLAPE BY TAGA


0010000
1000000
V.3 float and precision
Denotes the number of digits after the decimal.
#include <stdio.h>
#include <stdlib.h>
int main() {
float pi = 3.14159265;
printf( "%.3f\n", pi );
printf( "%.10f\n", pi );
return 0;
}
prints
3.142
3.1415927410
V.4 printf () AND SPECIAL CHARACTERS

The special characters in C can be found in the following table:

VI- Declarations
All variables must b e declared before they are used. They must be declared at the top of a
block (a
section of code enclosed in brackets { and }) before any statements. They may be initialised
by a
constant or an expression when declared. The following are a set of example declarations

int lower, upper, step; /* 3 uninitialised ints */


char tab = '\t'; /* a char initialised with ’\t’ */
char buf[10]; /* an uninitialised array of chars */
int m = 2+3+4; /* constant expression: 9 */
int n = m + 5; /* initialised with 9+5 = 14 */

LEVEL I COURSE OF STRUCTURED PROGRAMING ISLAPE BY TAGA


float limit = 9.34f;
const double PI = 3.1416;
The general form of a declaration6 is
<qualifier> <type> <identifier1> = <value1>, <identifier2> = <value2>, ... ;
where the assignment to an initial value is optional

VII- Arithmetic operations


VII.1 Relational and Logical Operations
There are six relational operators: greater-than >, less-than <, greater-than-or-equal-to >=,
lessthan-or-equal-to <=, equal-to == and not-equal-to !=. Relational expressions evaluate to 1
if they are TRUE and 0 if they are FALSE. For example, 2.1 < 7 evaluates to one, and x != x
evaluates to zero.
note. A very common programming error is to mistakenly type = (assignment) for ==
(equality).
For example, consider a loop that is to execute while ever x == 3. If it is written as
The three logical operators are AND && and OR || and NOT ! . All the relational and logical
operators are binary except the ! , which is unary. The && and || operators connect pairs of
conditional expressions, with && being TRUE only if both expressions are TRUE, and ||
being
TRUE if either expression is TRUE. They can be used to chain together multiple expressions,
as in
the following example where, given the integer values a=1, b=2, c=3, d=3,

VII.2 Bitwise Operators

Assignment Operators
Expressions involving the arithmetic or bitwise operators often involve the assignment
operator = (for example, z = x + y). Sometimes in these expressions, the left-hand-side
variable is repeated immediately on the right (e.g., x = x + y). These types of expression can
be written in the compressed form x += y, where the operator += is called an assignment
operator.
The binary arithmetic operators, +, −, *, /, and %, each have a corresponding assignment
operator +=, -=, *=, /=, and %=. Thus, we can write x *= y + 1 rather than x = x * (y + 1) .
For we mention also the bitwise assignment op erators: &=, |=, ^=, <<=, and >>=. We
return to the bitwise operators in Chapter 12.

LEVEL I COURSE OF STRUCTURED PROGRAMING ISLAPE BY TAGA

You might also like