C Is A General

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

C is a general-purpose high level language that was originally developed by Dennis Ritchie for the Unix operating system.

It was first implemented on the Digital Equipment Corporation PDP-11 computer in 1972. The Unix operating system and virtually all Unix applications are written in the C language. C has now become a widely used professional language for various reasons.

Easy to learn Structured language It produces efficient programs. It can handle low-level activities. It can be compiled on a variety of computers.

I.

Facts about C
C was invented to write an operating system called UNIX. C is a successor of B language which was introduced around 1970 The language was formalized in 1988 by the American National Standard Institue (ANSI). By 1973 UNIX OS almost totally written in C. Today C is the most widely used System Programming Language. Most of the state of the art software have been implemented using C

II.

Why to use C ?

C was initially used for system development work, in particular the programs that make-up the operating system. C was adoped as a system development language because it produces code that runs nearly as fast as code written in assembly language. Some examples of the use of C might be:

Operating Systems Language Compilers Assemblers Text Editors Print Spoolers Network Drivers Modern Programs Data Bases Language Interpreters Utilities

III.

C Program File

All the C programs are writen into text files with extension ".c" for example hello.c. You can use "vi" editor to write your C program into a file. This tutorial assumes that you know how to edit a text file and how to write programming insturctions inside a program file.

IV.

C Compilers

When you write any program in C language then to run that program you need to compile that program using a C Compiler which converts your program into a language understandable by a computer. This is called machine language (ie. binary format). So before proceeding, make sure you have C Compiler available at your computer. It comes alongwith all flavors of Unix and Linux.

If you are working over Unix or Linux then you can type gcc -v or cc -v and check the result. You can ask your system administrator or you can take help from anyone to identify an available C Compiler at your computer. If you don't have C compiler installed at your computer then you can use below given link to download a GNU C Compiler and use it. A C program basically has the following form:

Preprocessor Commands Functions Variables Statements & Expressions Comments

The following program is written in the C programming language. Open a text file hello.c using vi editor and put the following lines inside that file.

#include <stdio.h> int main() { /* My first program */ printf("Hello, World! \n"); return 0; }

Preprocessor Commands: These commands tells the compiler to do preprocessing before doing actual compilation. Like #include <stdio.h> is a preprocessor command which tells a C compiler to include stdio.h file before going to actual compilation. You will learn more about C Preprocessors in C Preprocessors session. Functions: are main building blocks of any C Program. Every C Program will have one or more functions and there is one mandatory function which is called main() function. This function is prefixed with keyword int which means this function returns an integer value when it exits. This integer value is retured using return statement. The C Programming language provides a set of built-in functions. In the above example printf()is a C built-in function which is used to print anything on the screen. Check Builtin functionsection for more detail. You will learn how to write your own functions and use them in Using Function session. Variables: are used to hold numbers, strings and complex data for manipulation. You will learn in detail about variables in C Variable Types. Statements & Expressions : Expressions combine variables and constants to create new values. Statements are expressions, assignments, function calls, or control flow statements which make up C programs. Comments: are used to give additional useful information inside a C Program. All the comments will be put inside /*...*/ as given in the example above. A comment can span through multiple lines.

V.

Note the followings

C is a case sensitive programming language. It means in C printf and Printf will have different meanings. C has a free-form line structure. End of each C statement must be marked with a semicolon. Multiple statements can be one the same line. White Spaces (ie tab space and space bar ) are ignored. Statements can continue over multiple lines.

VI.

C Program Compilation

To compile a C program you would have to Compiler name and program files name. Assuming your compiler's name is cc and program file name is hello.c, give following command at Unix prompt.

$cc hello.c
This will produce a binary file called a.out and an object file hello.o in your current directory. Here a.out is your first program which you will run at Unix prompt like any other system program. If you don't like the name a.out then you can produce a binary file with your own name by using -o option while compiling C program. See an example below

$cc -o hello hello.c


Now you will get a binary with name hello. Execute this program at Unix prompt but before executing / running this program make sure that it has execute permission set. If you don't know what is execute permission then just follow these two steps

$chmod 755 hello $./hello This will produce following result Hello, World
Congratulations!! you have written your first program in "C". Now believe me its not difficult to learn "C". The following names are reserved by the C language. Their meaning is already defined, and they cannot be re-defined to mean anything else. auto break case char const continue default do double While naming your functions and variables, other than these names, you can choose any names of reasonable length for variables, functions etc. else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while _Packed

C has a concept of 'data types' which are used to define a variable before its use. The definition of a variable will assign storage for the variable and define the type of data that will be held in the location. The value of a variable can be changed any time. C has the following basic built-in datatypes.

int float double char

Please note that there is not a boolean data type. C does not have the traditional view about logical comparison, but thats another story.

VII.

int - data type

int is used to define integer numbers.

{ int Count; Count = 5; }

VIII.

float - data type

float is used to define floating point numbers.

{ float Miles; Miles = 5.6; }

IX.

double - data type

double is used to define BIG floating point numbers. It reserves twice the storage for the number. On PCs this is likely to be 8 bytes.

{ double Atoms; Atoms = 2500000; }

X.

char - data type

char defines characters.

{ char Letter; Letter = 'x'; }

XI.

Modifiers

The data types explained above have the following modifiers.

short long signed unsigned

The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is not cast in stone. ANSI has the following rules:

short int <= int <= long int float <= double <= long double

What this means is that a 'short int' should assign less than or the same amount of storage as an 'int' and the 'int' should be less or the same bytes than a 'long int'. What this means in the real world is:

Type Bytes Range --------------------------------------------------------------------short int 2 -32,768 -> +32,767 (32kb) unsigned short int 2 0 -> +65,535 (64Kb) unsigned int 4 0 -> +4,294,967,295 ( 4Gb) int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb) long int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb) signed char 1 -128 -> +127 unsigned char 1 0 -> +255 float 4 double 8 long double 12
These figures only apply to todays generation of PCs. Mainframes and midrange machines could use different figures, but would still comply with the rule above. You can find out how much storage is allocated to a data type by using the sizeof operator discussed in Operator Types Session. Here is an example to check size of memory taken by various datatypes.

int main() { printf("sizeof(char) == %d\n", sizeof(char)); printf("sizeof(short) == %d\n", sizeof(short)); printf("sizeof(int) == %d\n", sizeof(int)); printf("sizeof(long) == %d\n", sizeof(long)); printf("sizeof(float) == %d\n", sizeof(float)); printf("sizeof(double) == %d\n", sizeof(double)); printf("sizeof(long double) == %d\n", sizeof(long double)); printf("sizeof(long long) == %d\n", sizeof(long long)); return 0; }

XII.

Qualifiers

A type qualifier is used to refine the declaration of a variable, a function, and parameters, by specifying whether:

The value of a variable can be changed. The value of a variable must always be read from memory rather than from a register

Standard C language recognizes the following two qualifiers:

const volatile

The const qualifier is used to tell C that the variable value can not change after initialisation. const float pi=3.14159; Now pi cannot be changed at a later time within the program. Another way to define constants is with the #define preprocessor which has the advantage that it does not use any storage The volatile qualifier declares a data type that can have its value changed in ways outside the control or detection of the compiler (such as a variable updated by the system clock or by another program). This prevents the compiler from optimizing code referring to the object by storing the object's value in a register and re-reading it from there, rather than from memory, where it may have changed. You will use this qualifier once you will become expert in "C". So for now just proceed.

XIII. What are Arrays:


We have seen all basic data types. In C language it is possible to make arrays whose elements are basic types. Thus we can make an array of 10 integers with the declaration.

int x[10];
The square brackets mean subscripting; parentheses are used only for function references. Array indexes begin at zero, so the elements of x are: Thus Array are special type of variables which can be used to store multiple values of same data type. Those values are stored and accessed using subscript or index. Arrays occupy consecutive memory slots in the computer's memory.

x[0], x[1], x[2], ..., x[9]


If an array has n elements, the largest subscript is n-1. Multiple-dimension arrays are provided. The declaration and use look like:

int name[10] [20]; n = name[i+j] [1] + name[k] [2];


Subscripts can be arbitrary integer expressions. Multi-dimension arrays are stored by row so the rightmost subscript varies fastest. In above example name has 10 rows and 20 columns.

Same way, arrays can be defined for any data type. Text is usually kept as an array of characters. By convention in C, the last character in a character array should be a `\0' because most programs that manipulate character arrays expect it. For example, printf uses the `\0' to detect the end of a character array when printing it out with a `%s'. Here is a program which reads a line, stores it in a buffer, and prints its length (excluding the newline at the end).

main( ) { int n, c; char line[100]; n = 0; while( (c=getchar( )) != '\n' ) { if( n < 100 ) line[n] = c; n++; } printf("length = %d\n", n); }

XIV.

Array Initialization
As with other declarations, array declarations can include an optional initialization Scalar variables are initialized with a single value Arrays are initialized with a list of values The list is enclosed in curly braces

int array [8] = {2, 4, 6, 8, 10, 12, 14, 16};


The number of initializers cannot be more than the number of elements in the array but it can be less in which case, the remaining elements are initialized to 0.if you like, the array size can be inferred from the number of initializers by leaving the square brackets empty so these are identical declarations:

int array1 [8] = {2, 4, 6, 8, 10, 12, 14, 16}; int array2 [] = {2, 4, 6, 8, 10, 12, 14, 16};
An array of characters ie string can be initialized as follows:

char string[10] = "Hello";


A variable is just a named area of storage that can hold a single value (numeric or character). The C language demands that you declare the name of each variable that you are going to use and its type, or class, before you actually try to do anything with it. The Programming language C has two main variable types

Local Variables Global Variables

XV.

Local Variables
Local variables scope is confined within the block or function where it is defined. Local variables must always be defined at the top of a block. When a local variable is defined - it is not initalised by the system, you must initalise it yourself.

When execution of the block starts the variable is available, and when the block ends the variable 'dies'.

Check following example's output

main() { int i=4; int j=10; i++; if (j > 0) { /* i defined in 'main' can be seen */ printf("i is %d\n",i); } if (j > 0) { /* 'i' is defined and so local to this block */ int i=100; printf("i is %d\n",i); }/* 'i' (value 100) dies here */ printf("i is %d\n",i); /* 'i' (value 5) is now visable.*/ } This i is i is i is will generate following output 5 100 5

Here ++ is called incremental operator and it increase the value of any integer variable by 1. Thus i++ is equivalent to i = i + 1; You will see -- operator also which is called decremental operator and it idecrease the value of any integer variable by 1. Thus i-- is equivalent to i = i - 1;

XVI.

Global Variables

Global variable is defined at the top of the program file and it can be visible and modified by any function that may reference it. Global variables are initalised automatically by the system when you define them! Data Type int char float pointer Initialser 0 '\0' 0 NULL

If same variable name is being used for global and local variable then local variable takes preference in its scope. But it is not a good practice to use global variables and local variables with the same name.

int i=4;

/* Global definition

*/

main() { i++; /* Global variable */ func(); printf( "Value of i = %d -- main function\n", i ); } func() { int i=10; /* Local definition */ i++; /* Local variable */ printf( "Value of i = %d -- func() function\n", i ); } This will produce following result Value of i = 11 -- func() function Value of i = 5 -- main function
i in main function is global and will be incremented to 5. i in func is internal and will be incremented to 11. When control returns to main the internal variable will die and and any reference to i will be to the global. A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program. There are following storage classes which can be used in a C Program

auto register static extern

XVII. auto - Storage Class


auto is the default storage class for all local variables.

{ int Count; auto int Month; }


The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables.

XVIII. register - Storage Class


register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location).

{ register int }
Register should only be used for variables that require quick access - such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register - depending on hardware and implimentation restrictions.

Miles;

XIX.

static - Storage Class

static is the default storage class for global variables. The two variables below (count and road) both have a static storage class.

static int Count; int Road; { printf("%d\n", Road); }


static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in. static can also be defined within a function. If this is done the variable is initalised at run time but is not reinitalized when the function is called. This inside a function static variable retains its value during vairous calls.

void func(void); static count=10; /* Global variable - static is the default */ main() { while (count--) { func(); } } void func( void ) { static i = 5; i++; printf("i is %d and count is %d\n", i, count); } This will produce following result i i i i i i i i i i is is is is is is is is is is 6 and count is 9 7 and count is 8 8 and count is 7 9 and count is 6 10 and count is 5 11 and count is 4 12 and count is 3 13 and count is 2 14 and count is 1 15 and count is 0

NOTE : Here keyword void means function does not return anything and it does not take any parameter. You can memoriese void as nothing. static variables are initialized to 0 automatically. Definition vs Declaration : Before proceeding, let us understand the difference betweendefintion and declaration of a variable or function. Definition means where a variable or function is defined in realityand actual memory is allocated for variable or function. Declaration means just giving a

reference of a variable and function. Through declaration we assure to the complier that this variable or function has been defined somewhere else in the program and will be provided at the time of linking. In the above examples char *func(void) has been put at the top which is a declaration of this function where as this function has been defined below to main()function. There is one more very important use for 'static'. Consider this bit of code.

char *func(void); main() { char *Text1; Text1 = func(); } char *func(void) { char Text2[10]="martin"; return(Text2); }
Now, 'func' returns a pointer to the memory location where 'text2' starts BUT text2 has a storage class of 'auto' and will disappear when we exit the function and could be overwritten but something else. The answer is to specify

static char Text[10]="martin";


The storage assigned to 'text2' will remain reserved for the duration if the program.

XX.

extern - Storage Class

extern is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initalized as all it does is point the variable name at a storage location that has been previously defined. When you have multiple files and you define a global variable or function which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to decalre a global variable or function in another files. File 1: main.c

int count=5; main() { write_extern(); }


File 2: write.c

void write_extern(void); extern int count; void write_extern(void) { printf("count is %i\n", count);

}
Here extern keyword is being used to declare count in another file. Now compile these two files as follows

gcc main.c write.c -o write


This fill produce write program which can be executed to produce result. Count in 'main.c' will have a value of 5. If main.c changes the value of count - write.c will see the new value A C constant is usually just the written version of a number. For example 1, 0, 5.73, 12.5e9. We can specify our constants in octal or hexadecimal, or force them to be treated as long integers.

Octal constants are written with a leading zero - 015. Hexadecimal constants are written with a leading 0x - 0x1ae. Long constants are written with a trailing L - 890L.

Character constants are usually just the character enclosed in single quotes; 'a', 'b', 'c'. Some characters can't be represented in this way, so we use a 2 character sequence as follows.

'\n' '\t' '\\' '\'' '\0'

newline tab backslash single quote null ( Usedautomatically to terminate character string )

In addition, a required bit pattern can be specified using its octal equivalent. '\044' produces bit pattern 00100100. Character constants are rarely used, since string constants are more convenient. A string constant is surrounded by double quotes eg "Brian and Dennis". The string is actually stored as an array of characters. The null character '\0' is automatically placed at the end of such a string to act as a string terminator. A character is a different type to a single character string. This is important poing to note.

XXI. Defining Constants


ANSI C allows you to declare constants. When you declare a constant it is a bit like a variable declaration except the value cannot be changed. The const keyword is to declare a constant, as shown below:

int const a = 1; const int a =2;


Note:

You can declare the const before or after the type. Choose one an stick to it. It is usual to initialise a const with a value as it cannot get a value any other way.

The preprocessor #define is another more flexible (see Preprocessor Chapters) method to defineconstants in

a program.

#define TRUE #define FALSE #define NAME_SIZE

1 0 20

Here TRUE, FALSE and NAME_SIZE are constant You frequently see const declaration in function parameters. This says simply that the function isnot going to change the value of the parameter. The following function definition used concepts we have not met (see chapters on functions, strings, pointers, and standard libraries) but for completenes of this section it is is included here:

void strcpy(char *buffer, char const *string)

XXII. The enum Data type


enum is the abbreviation for ENUMERATE, and we can use this keyword to declare and initialize a sequence of integer constants. Here's an example:

enum colors {RED, YELLOW, GREEN, BLUE};


I've made the constant names uppercase, but you can name them which ever way you want. Here, colors is the name given to the set of constants - the name is optional. Now, if you don't assign a value to a constant, the default value for the first one in the list - RED in our case, has the value of 0. The rest of the undefined constants have a value 1 more than the one before, so in our case, YELLOW is 1, GREEN is 2 and BLUE is 3. But you can assign values if you wanted to:

enum colors {RED=1, YELLOW, GREEN=6, BLUE };


Now RED=1, YELLOW=2, GREEN=6 and BLUE=7. The main advantage of enum is that if you don't initialize your constants, each one would have a unique value. The first would be zero and the rest would then count upwards. You can name your constants in a weird order if you really wanted...

#include <stdio.h> int main() { enum {RED=5, YELLOW, GREEN=4, BLUE}; printf("RED = %d\n", RED); printf("YELLOW = %d\n", YELLOW); printf("GREEN = %d\n", GREEN); printf("BLUE = %d\n", BLUE); return 0; } This will produce following results

RED = 5 YELLOW = 6 GREEN = 4 BLUE = 5


What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. C language supports following type of operators.

Arithmetic Operators Logical (or Relational) Operators Bitwise Operators Assignment Operators Misc Operators

Lets have a look on all operators one by one. XXIII. Arithmetic Operators:

There are following arithmetic operators supported by C language: Assume variable A holds 10 and variable B holds 20 then: Show Examples Operator + * / % ++ -Description Adds two operands Subtracts second operand from the first Multiply both operands Divide numerator by denumerator Modulus Operator and remainder of after an integer division Increment operator, increases integer value by one Decrement operator, decreases integer value by one Logical (or Relational) Operators: A + B will give 30 A - B will give -10 A * B will give 200 B / A will give 2 B % A will give 0 A++ will give 11 A-- will give 9 Example

XXIV.

There are following logical operators supported by C language Assume variable A holds 10 and variable B holds 20 then: Show Examples Operator == != Description Checks if the value of two operands is equal or not, if yes then condition becomes true. Checks if the value of two operands is equal or not, if values are not equal then condition Example (A == B) is not true. (A != B) is true.

becomes true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. Called Logical AND operator. If both the operands are non zero then then condition becomes true. Called Logical OR Operator. If any of the two operands is non zero then then condition becomes true. Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. Bitwise Operators: (A > B) is not true.

<

(A < B) is true.

>=

(A >= B) is not true.

<=

(A <= B) is true.

&&

(A && B) is true.

||

(A || B) is true.

!(A && B) is false.

XXV.

Bitwise operator works on bits and perform bit by bit operation. Assume if A = 60; and B = 13; Now in binary format they will be as follows: A = 0011 1100 B = 0000 1101 ----------------A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011 Show Examples There are following Bitwise operators supported by C language Operator Description Example

& | ^ ~ <<

Binary AND Operator copies a bit to the result if it exists in both operands. Binary OR Operator copies a bit if it exists in eather operand. Binary XOR Operator copies the bit if it is set in one operand but not both. Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. Assignment Operators:

(A & B) will give 12 which is 0000 1100 (A | B) will give 61 which is 0011 1101 (A ^ B) will give 49 which is 0011 0001 (~A ) will give -60 which is 1100 0011 A << 2 will give 240 which is 1111 0000

>>

A >> 2 will give 15 which is 0000 1111

XXVI.

There are following assignment operators supported by C language: Show Examples Operator = Description Simple assignment operator, Assigns values from right side operands to left side operand Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand Left shift AND assignment operator Right shift AND assignment operator Bitwise AND assignment operator Example C = A + B will assigne value of A + B into C

+=

C += A is equivalent to C = C + A

-=

C -= A is equivalent to C = C - A

*=

C *= A is equivalent to C = C * A

/=

C /= A is equivalent to C = C / A

%=

C %= A is equivalent to C = C % A

<<= >>= &=

C <<= 2 is same as C = C << 2 C >>= 2 is same as C = C >> 2 C &= 2 is same as C = C & 2

^= |=

bitwise exclusive OR and assignment operator bitwise inclusive OR and assignment operator

C ^= 2 is same as C = C ^ 2 C |= 2 is same as C = C | 2

XXVII. Short Notes on L-VALUE and R-VALUE: x = 1; takes the value on the right (e.g. 1) and puts it in the memory referenced by x. Here x and 1 are known as L-VALUES and R-VALUES respectively L-values can be on either side of the assignment operator where as R-values only appear on the right. So x is an L-value because it can appear on the left as we've just seen, or on the right like this: y = x; However, constants like 1 are R-values because 1 could appear on the right, but 1 = x; is invalid. XXVIII. Misc Operators There are few other operators supported by C Language. Show Examples Operator sizeof() & * ?: Description Returns the size of an variable. Returns the address of an variable. Pointer to a variable. Conditional Expression Example sizeof(a), where a is interger, will return 4. &a; will give actaul address of the variable. *a; will pointer to a variable. If Condition is true ? Then value X : Otherwise value Y

XXIX.

Operators Categories:

All the operators we have discussed above can be categorised into following categories:


XXX.

Postfix operators, which follow a single operand. Unary prefix operators, which precede a single operand. Binary operators, which take two operands and perform a variety of arithmetic and logical operations. The conditional operator (a ternary operator), which takes three operands and evaluates either the second or third expression, depending on the evaluation of the first expression. Assignment operators, which assign a value to a variable. The comma operator, which guarantees left-to-right evaluation of comma-separated expressions.

Precedence of C Operators:

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator: For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedenace than + so it first get multiplied with 3*2 and then adds into 7. Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedenace operators will be evaluated first.

Category Postfix Unary Multiplicative Additive Shift Relational Equality Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional Assignment Comma () [] -> . ++ - -

Operator

Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left Right to left Left to right

+ - ! ~ ++ - - (type) * & sizeof */% +<< >> < <= > >= == != & ^ | && || ?: = += -= *= /= %= >>= <<= &= ^= |= ,

Input : In any programming language input means to feed some data into program. This can be given in the form of file or from command line. C programming language provides a set of built-in functions to read given input and feed it to the program as per requirement. Output : In any programming language output means to display some data on screen, printer or in any file. C programming language provides a set of built-in functions to output required data. Here we will discuss only one input function and one putput function just to understand the meaning of input and output. Rest of the functions are given into C - Built-in Functions

XXXI. printf() function


This is one of the most frequently used functions in C for output. ( we will discuss what is function in subsequent chapter. ). Try following program to understand printf() function.

#include <stdio.h> main() { int dec = 5; char str[] = "abc"; char ch = 's'; float pi = 3.14; printf("%d %s %f %c\n", dec, str, pi, } ch);

The output of the above would be:

5 abc 3.140000 c
Here %d is being used to print an integer, %s is being usedto print a string, %f is being used to print a float and %c is being used to print a character. A complete syntax of printf() function is given in C - Built-in Functions

XXXII. scanf() function


This is the function which can be used to to read an input from the command line. Try following program to understand scanf() function.

#include <stdio.h> main() { int x; int args; printf("Enter an integer: "); if (( args = scanf("%d", &x)) == 0) { printf("Error: not an integer\n"); } else { printf("Read in %d\n", x); } }
Here %d is being used to read an integer value and we are passing &x to store the vale read input. Here &indicates the address of variavle x. This program will prompt you to enter a value. Whatever value you will enter at command prompt that will be output at the screen using printf() function. If you eneter a non-integer value then it will display an error message.

Enter an integer: 20 Read in 20


A complete set of input output functions is given in C - Built-in Functions A pointer is a special kind of variable. Pointers are designed for storing memory address i.e. the address of another variable. Declaring a pointer is the same as declaring a normal variable except you stick an asterisk '*' in front of the variables identifier.

There are two new operators you will need to know to work with pointers. The "address of" operator '&' and the "dereferencing" operator '*'. Both are prefix unary operators. When you place an ampersand in front of a variable you will get it's address, this can be stored in a pointer vairable. When you place an asterisk in front of a pointer you will get the value at the memory address pointed to.

Here is an example to understand what I have stated above.

#include <stdio.h> int main() { int my_variable = 6, other_variable = 10; int *my_pointer; printf("the address of my_variable is : %p\n", &my_variable); printf("the address of other_variable is : %p\n", &other_variable); my_pointer = &my_variable; printf("\nafter \"my_pointer = &my_variable\":\n"); printf("\tthe value of my_pointer is %p\n", my_pointer); printf("\tthe value at that address is %d\n", *my_pointer); my_pointer = &other_variable; printf("\nafter \"my_pointer = &other_variable\":\n"); printf("\tthe value of my_pointer is %p\n", my_pointer); printf("\tthe value at that address is %d\n", *my_pointer); return 0; }
This will produce following result.

the address of my_variable is : 0xbfffdac4 the address of other_variable is : 0xbfffdac0 after "my_pointer = &my_variable": the value of my_pointer is 0xbfffdac4 the value at that address is 6 after "my_pointer = &other_variable": the value of my_pointer is 0xbfffdac0 the value at that address is 10

XXXIII.

Pointers and Arrays

The most frequent use of pointers in C is for walking efficiently along arrays. In fact, in the implementation of an array, the array name represents the address of the zeroth element of the array, so you can't use it on the left side of an expression. For example:

char *y; char x[100];


y is of type pointer to character (although it doesn't yet point anywhere). We can make y point to an element of x by either of

y = &x[0]; y = x;
Since x is the address of x[0] this is legal and consistent. Now `*y' gives x[0]. More importantly notice the following:

*(y+1) *(y+i)

gives x[1] gives x[i]

and the sequence y = &x[0]; y++; leaves y pointing at x[1].

XXXIV.

Pointer Arithmetic:

C is one of the few languages that allows pointer arithmetic. In other words, you actually move the pointer reference by an arithmetic operation. For example:

int x = 5, *ip = &x; ip++;


On a typical 32-bit machine, *ip would be pointing to 5 after initialization. But ip++; increments the pointer 32-bits or 4-bytes. So whatever was in the next 4-bytes, *ip would be pointing at it. Pointer arithmetic is very useful when dealing with arrays, because arrays and pointers share a special relationship in C.

XXXV.

Using Pointer Arithmetic With Arrays:

Arrays occupy consecutive memory slots in the computer's memory. This is where pointer arithmetic comes in handy - if you create a pointer to the first element, incrementing it one step will make it point to the next element.

#include <stdio.h> int main() { int *ptr; int arrayInts[10] = {1,2,3,4,5,6,7,8,9,10}; ptr = arrayInts; /* ptr = &arrayInts[0]; is also fine */ printf("The pointer is pointing to the first "); printf("array element, which is %d.\n", *ptr); printf("Let's increment it.....\n"); ptr++; printf("Now it should point to the next element,"); printf(" which is %d.\n", *ptr); printf("But suppose we point to the 3rd and 4th: %d %d.\n", *(ptr+1),*(ptr+2)); ptr+=2; printf("Now skip the next 4 to point to the 8th: %d.\n", *(ptr+=4));

ptr--; printf("Did I miss out my lucky number %d?!\n", *(ptr++)); printf("Back to the 8th it is then..... %d.\n", *ptr); return 0; }
This will produce following result:

The pointer is pointing to the first array element, which is 1. Let's increment it..... Now it should point to the next element, which is 2. But suppose we point to the 3rd and 4th: 3 4. Now skip the next 4 to point to the 8th: 8. Did I miss out my lucky number 7?! Back to the 8th it is then..... 8.
See more examples on Pointers and Array

XXXVI.

Pointers and const Type Qualifier:

The const type qualifier can make things a little confusing when it is used with pointer declarations. The below example:

const int * const ip; int * const ip; const int * ip; int * ip;

/* The pointer *ip is const and it points at is also cont */ /* The pointer *ip is const /* What *ip is pointing at is const /* Nothing is const

*/ */ */

As you can see, you must be careful when specifying the const qualifier when using pointers.

XXXVII.

Modifying Variables Using Pointers:

You know how to access the value pointed to using the dereference operator, but you can also modify the content of variables. To achieve this, put the dereferenced pointer on the left of the assignment operator, as shown in this example, which uses an array:

#include <stdio.h> int main() { char *ptr; char arrayChars[8] = {'F','r','i','e','n','d','s','\0'}; ptr = arrayChars; printf("The array reads %s.\n", arrayChars); printf("Let's change it..... "); *ptr = 'f'; /* ptr points to the first element */ printf(" now it reads %s.\n", arrayChars); printf("The 3rd character of the array is %c.\n",

*(ptr+=2)); printf("Let's change it again..... "); *(ptr - 1) = ' '; printf("Now it reads %s.\n", arrayChars); return 0; }
This will produce following result:

The array reads Friends. Let's change it..... now it reads friends. The 3rd character of the array is i. Let's change it again..... Now it reads f iends.

XXXVIII.

Generic Pointers: ( void Pointer )

When a variable is declared as being a pointer to type void it is known as a generic pointer. Since you cannot have a variable of type void, the pointer will not point to any data and therefore cannot be dereferenced. It is still a pointer though, to use it you just have to cast it to another kind of pointer first. Hence the term Generic pointer. This is very useful when you want a pointer to point to data of different types at different times. Try the following code to understand Generic Pointers.

#include <stdio.h> int main() { int i; char c; void *the_data; i = 6; c = 'a'; the_data = &i; printf("the_data points to the integer value %d\n", *(int*) the_data); the_data = &c; printf("the_data now points to the character %c\n", *(char*) the_data); return 0; }
NOTE-1 : Here in first print statement, the_data is prefixed by *(int*). This is called type casting in C language.Type is used to caste a variable from one data type to another datatype to make it compatible to the lvalue. NOTE-2 : lvalue is something which is used to left side of a statement and in which we can assign some value. A constant can't be an lvalue because we can not assign any value in contact. For example x = y, here x is lvalue and y is rvalue.

However, above example will produce following result:

the_data points to the integer value 6 the_data now points to the character a

In C language Strings are defined as an array of characters or a pointer to a portion of memory containing ASCII characters. A string in C is a sequence of zero or more characters followed by a NULL '\0' character: It is important to preserve the NULL terminating character as it is how C defines and manages variable length strings. All the C standard library functions require this for successful operation. All the string handling functions are prototyped in: string.h or stdio.h standard header file. So while using any string related function, don't forget to include either stdio.h or string.h. May be your compiler differes so please check before going ahead. If you were to have an array of characters WITHOUT the null character as the last element, you'd have an ordinary character array, rather than a string constant. String constants have double quote marks around them, and can be assigned to char pointers as shown below. Alternatively, you can assign a string constant to a char array - either with no size specified, or you can specify a size, but don't forget to leave a space for the null character!

char *string_1 = "Hello"; char string_2[] = "Hello"; char string_3[6] = "Hello";

XXXIX.

Reading and Writing Strings:

One possible way to read in a string is by using scanf. However, the problem with this, is that if you were to enter a string which contains one or more spaces, scanf would finish reading when it reaches a space, or if return is pressed. As a result, the string would get cut off. So we could use the gets function A gets takes just one argument - a char pointer, or the name of a char array, but don't forget to declare the array / pointer variable first! What's more, is that it automatically prints out a newline character, making the output a little neater. A puts function is similar to gets function in the way that it takes one argument - a char pointer. This also automatically adds a newline character after printing out the string. Sometimes this can be a disadvantage, so printf could be used instead.

#include <stdio.h> int main() { char array1[50]; char *array2; printf("Now enter another string less than 50"); printf(" characters with spaces: \n"); gets(array1); printf("\nYou entered: "); puts(array1); printf("\nTry entering a string less than 50"); printf(" characters, with spaces: \n"); scanf("%s", array2); printf("\nYou entered: %s\n", array2);

return 0; }
This will produce following result:

Now enter another string less than 50 characters with spaces: hello world You entered: hello world Try entering a string less than 50 characters, with spaces: hello world You entered: hello

XL.

String Manipulation Functions


char *strcpy (char *dest, char *src) - Copy src string string into dest string. char *strncpy(char *string1, char *string2, int n) - Copy first n characters of string2 to stringl . int strcmp(char *string1, char *string2) - Compare string1 and string2 to determine alphabetic order. int strncmp(char *string1, char *string2, int n) - Compare first n characters of two strings. int strlen(char *string) - Determine the length of a string. char *strcat(char *dest, const char *src); - Concatenate string src to the string dest. char *strncat(char *dest, const char *src, int n); - Concatenate n chracters from string src to the string dest. char *strchr(char *string, int c) - Find first occurrence of character c in string. char *strrchr(char *string, int c) - Find last occurrence of character c in string. char *strstr(char *string2, char string*1) - Find first occurrence of string string1 in string2. char *strtok(char *s, const char *delim) - Parse the string s into tokens using delim as delimiter.

You might also like