Sie sind auf Seite 1von 51

There are 3 main uses for the static.

1. If you declare within a function:


It retains the value between function calls

2.If it is declared for a function name:


By default function is extern..so it will be visible from other files if the function
declaration is as static..it is invisible for the outer files 

3. Static for global variables:


By default we can use the global variables from outside files If it is static
global..that variable is limited to with in the file.

#include <stdio.h>

int t = 10;  

main(){

    int x = 0; 
    void funct1();
    funct1();            
    printf("After first call \n");
    funct1();            
    printf("After second call \n");
    funct1();            
    printf("After third call \n");

}
void funct1()
{
    static int y = 0;  
    int z = 10;             
    printf("value of y %d z %d",y,z);
    y=y+10;
}
 

value of y 0 z 10 After first call


value of y 10 z 10 After second call
value of y 20 z 10 After third call

Can a variable be both constant and volatile?

Yes. The const modifier means that this code cannot change the value of the
variable, but that does not mean that the value cannot be changed by means
outside this code. For instance, in the example in FAQ 8, the timer structure was
accessed through a volatile const pointer.

The function itself did not change the value of the timer, so it was declared const.
However, the value was changed by hardware on the computer, so it was
declared volatile. If a variable is both const and volatile, the two modifiers can
appear in either order.

C has three types of storage: automatic, static and allocated. 

Variable having block scope and without static specifier have automatic storage
duration. 

Variables with block scope, and with static specifier have static scope. Global
variables (i.e, file scope) with or without the the static specifier also have static
scope. 

Memory obtained from calls to malloc(), alloc() or realloc() belongs to allocated


storage class.

 
Can include files be nested?

Yes. Include files can be nested any number of times. As long as you use
precautionary measures , you can avoid including the same file twice. In the past,
nesting header files was seen as bad programming practice, because it
complicates the dependency tracking function of the MAKE program and thus
slows down compilation. Many of today’s popular compilers make up for this
difficulty by implementing a concept called precompiled headers, in which all
headers and associated dependencies are stored in a precompiled state.

Many programmers like to create a custom header file that has #include
statements for every header needed for each module. This is perfectly acceptable
and can help avoid potential problems relating to #include files, such as
accidentally omitting an #include file in a module.

What is the stack?

The stack is where all the functions’ local (auto) variables are created. The stack
also contains some information used to call and return from functions.

A stack trace is a list of which functions have been called, based on this
information. When you start using a debugger, one of the first things you should
learn is how to get a stack trace.

The stack is very inflexible about allocating memory; everything must be


deallocated in exactly the reverse order it was allocated in. For implementing
function calls, that is all that’s needed. Allocating memory off the stack is
extremely efficient. One of the reasons C compilers generate such good code is
their heavy use of a simple stack.

There used to be a C function that any programmer could use for allocating
memory off the stack. The memory was automatically deallocated when the
calling function returned. This was a dangerous function to call; it’s not available
anymore.

How do you use a pointer to a function ?

The hardest part about using a pointer-to-function is declaring it. 


Consider an example. You want to create a pointer, pf, that points to the strcmp()
function.

The strcmp() function is declared in this way: 


int strcmp(const char *, const char * )

To set up pf to point to the strcmp() function, you want a declaration that looks
just like the strcmp() function’s declaration, but that has *pf rather than strcmp: 
int (*pf)( const char *, const char * );

After you’ve gotten the declaration of pf, you can #include and assign the address
of strcmp() to pf: pf = strcmp;

What is the purpose of main( ) function ?

The function main( ) invokes other functions within it.It is the first function to be
called when the program starts execution.

 It is the starting function

 It returns an int value to the environment that called the program

 Recursive call is allowed for main( ) also.

 It is a user-defined function

 Program execution ends when the closing brace of the function main( ) is
reached.
 It has two arguments 1)argument count and 2) argument vector
(represents strings passed).

 Any user-defined name can also be used as parameters for main( ) instead
of argc and argv

What is the difference between calloc() and malloc() ?

1. calloc(...) allocates a block of memory for an array of elements of a certain size.


By default the block is initialized to 0. The total number of memory allocated will
be (number_of_elements * size).

malloc(...) takes in only a single argument which is the memory required in bytes.
malloc(...) allocated bytes of memory and not blocks of memory like calloc(...).

2. malloc(...) allocates memory blocks and returns a void pointer to the allocated
space, or NULL if there is insufficient memory available.

calloc(...) allocates an array in memory with elements initialized to 0 and returns a


pointer to the allocated space. calloc(...) calls malloc(...) in order to use the C++
_set_new_mode function to set the new handler mode.

What is the benefit of using an enum rather than a #define constant ?

The use of an enumeration constant (enum) has many advantages over using the
traditional symbolic constant style of #define. These advantages include a lower
maintenance requirement, improved program readability, and better debugging
capability.
1) The first advantage is that enumerated constants are generated automatically
by the compiler. Conversely, symbolic constants must be manually assigned
values by the programmer.
For instance, if you had an enumerated constant type for error codes that could
occur in your program, your enum definition could look something like this:
enum Error_Code
{
OUT_OF_MEMORY,
INSUFFICIENT_DISK_SPACE,
LOGIC_ERROR,
FILE_NOT_FOUND
};
In the preceding example, OUT_OF_MEMORY is automatically assigned the value
of 0 (zero) by the compiler because it appears first in the definition. The compiler
then continues to automatically assign numbers to the enumerated constants,
making INSUFFICIENT_DISK_SPACE equal to 1, LOGIC_ERROR equal to 2, and
FILE_NOT_FOUND equal to 3, so on.
If you were to approach the same example by using symbolic constants, your
code would look something like this:
#define OUT_OF_MEMORY 0
#define INSUFFICIENT_DISK_SPACE 1
#define LOGIC_ERROR 2
#define FILE_NOT_FOUND 3
values by the programmer. Each of the two methods arrives at the same result:
four constants assigned numeric values to represent error codes. Consider the
maintenance required, however, if you were to add two constants to represent
the error codes DRIVE_NOT_READY and CORRUPT_FILE. Using the enumeration
constant method, you simply would put these two constants anywhere in the
enum definition. The compiler would generate two unique values for these
constants. Using the symbolic constant method, you would have to manually
assign two new numbers to these constants. Additionally, you would want to
ensure that the numbers you assign to these constants are unique. 
2) Another advantage of using the enumeration constant method is that your
programs are more readable and thus can be understood better by others who
might have to update your program later.

3) A third advantage to using enumeration constants is that some symbolic


debuggers can print the value of an enumeration constant. Conversely, most
symbolic debuggers cannot print the value of a symbolic constant. This can be an
enormous help in debugging your program, because if your program is stopped at
a line that uses an enum, you can simply inspect that constant and instantly know
its value. On the other hand, because most debuggers cannot print #define
values, you would most likely have to search for that value by manually looking it
up in a header file.

C Interview Questions Part 17


C interview question:What is the difference between "calloc(...)" and
"malloc(...)"?
Answer:1. calloc(...) allocates a block of memory for an arrayof elements of a
certain size. By default the block is initialized to 0. The total number of memory
allocated will be (number_of_elements * size). malloc(...) takes in only a
singleargument which is the memory required in bytes. malloc(...) allocated bytes
of memory and not blocks of memory like calloc(...).
2. malloc(...) allocates memory blocks and returns a void pointer to the allocated
space, or NULL if there is insufficient memory available calloc(...) allocates
an array in memory with elements initialized to and returns a pointer to the
allocated space. calloc(...) calls malloc(...) in order to use the C++ _set_new_mode
function to set the new handler mode. 

C interview question:What is the difference between "printf(...)" and"sprintf(...)"?

Answer:sprintf(...) writes data to the character array whereas printf(...) writes


data to the
standard output device.

C interview question:What does static variable mean?


Answer:There are 3 main uses for the static.
1. If you declare within a function:It retains the value between function calls
2.If it is declared for a function name:By default function is extern..so it will be
visible from other files if the function declaration is as static..it is invisible for the
outer files
3. Static for global variables:By default we can use the global variables from
outside files If it is static global..that variable is limited to with in the file

C interview question:What are the differences between malloc() and calloc()?


Answer:There are 2 differences.First, is in the number of arguments. malloc()
takes a single argument(memory required in bytes), while calloc() needs 2
arguments(number of variables to allocate memory, size in bytes of a
single variable).Secondly, malloc() does not initialize the memory allocated, while
calloc() initializes the allocated memory to ZERO.

C interview question:Difference between const char* p and char const* p?


Answer:In const char* p, the character pointed by ‘p’ is constant, so u cant
change the value of character pointed by p but u can make ‘p’ refer to some other
location. in char const* p, the ptr ‘p’ is constant not the character referencedby it,
so u cant make ‘p’ to reference to any other location but u can change the value
of the char pointed by ‘p’.

C interview question:How can you determine the size of an allocated portion of


memory?
Answer:You can’t, really. free() can , but there’s no way for your program to know
the trick free() uses. Even if you disassemble the library and discover the trick,
there’s no guarantee the trick won’t change with the next release of thecompiler.

Posted by Siva kumar.T.A at 11:15 AM , Links to this post, 0 comments


A union is a way of providing an alternate way of describing the same memory
area. In this way, you could have a struct that contains a union, so that the
"static", or similar portion of the data is described first, and the portion that
changes is described by the union. The idea of a union could be handled in a
different way by having 2 different structs defined, and making a pointer to each
kind of struct. The pointer to struct "a" could be assigned to the value of a buffer,
and the pointer to struct "b" could be assigned to the same buffer, but now a-
>somefield and b->someotherfield are both located in the same buffer. That is the
idea behind a union. It gives different ways to break down the same buffer area.

  
The difference between structure and union in c are: 1. union allocates the
memory equal to the maximum memory required by the member of the union
but structure allocates the memory equal to the total memory required by the
members. 2. In union, one block is used by all the member of the union but in
case of structure, each member have their own memory space  

Read
more: http://wiki.answers.com/Q/What_are_the_differences_between_a_union_
and_a_structure_in_C#ixzz1WfqsWPsB

While structure enables us treat a number of different variables stored at


different in memory , a union enables us to treat the same space in memory as a
number of different variables. That is a Union offers a way for a section of
memory to be treated as a variable of one type on one occasion and as a different
variable of a different type on another occasion.
There is frequent rwquirement while interacting with hardware to access access a
byte or group of bytes simultaneously and sometimes each byte individually.
Usually union is the answer.
=======Difference With example***** Lets say a structure containing an int,char
and float is created and a union containing int char float are declared. struct
TT{ int a; float b; char c; } Union UU{ int a; float b; char c; }
sizeof TT(struct) would be >9 bytes (compiler dependent-if int,float, char are
taken as 4,4,1)
sizeof UU(Union) would be 4 bytes as supposed from above.If a variable in double
exists in union then the size of union and struct would be 8 bytes and cumulative
size of all variables in struct.  

Read
more: http://wiki.answers.com/Q/What_are_the_differences_between_a_union_
and_a_structure_in_C#ixzz1Wfqut4Oo

what is pointer?  

In c,a pointer is a variable that points to or references a memory location in which


data is stored. In the computer,each memory cell has an address that can be used
to access that location so a pointer variable points to a memory location we can
access and change the contents of this memory location via the pointer.

Pointer declaration:

A pointer is a variable that contains the memory location of another variable in


shich data is stored. Using pointer,you start by specifying the type of data stored
in the location. The asterisk helps to tell the compiler that you are creating a
pointer variable. Finally you have to give the name of the variable. The syntax is as
shown below.

type * variable name

The following example illustrate the declataion of pointer variable

int *ptr;
float *string;

Address operator:

Once we declare a pointer variable then we must point it to something we can do


this by assigning to the pointer the address of the variable you want to point as in
the following example:

ptr=&num;

The above code tells that the address where num is stores into the variable ptr.
The variable ptr has the value 21260,if num is stored in memory 21260 address
then

The following program illustrate the pointer declaration

/* A program to illustrate pointer declaration*/

main()
{
int *ptr;
int sum;
sum=45;
ptr=∑
printf (“\n Sum is %d\n”, sum);
printf (“\n The sum pointer is %d”, ptr);
}
Pointer expressions & pointer arithmetic:

In expressions,like other variables pointer variables can be used. For example if p1


and p2 are properly initialized and declared pointers, then the following
statements are valid.

y=*p1**p2;
sum=sum+*p1;
z= 5* – *p2/p1;
*p2= *p2 + 10;

C allows us to subtract integers to or add integers from pointers as well as to


subtract one pointer from the other. We can also use short hand operators with
pointers p1+=; sum+=*p2; etc., By using relational operators,we can also compare
pointers like the expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed.

The following program illustrate the pointer expression and pointer arithmetic

/*Program to illustrate the pointer expression and pointer arithmetic*/


#include< stdio.h >
main()
{ int ptr1,ptr2;
int a,b,x,y,z;
a=30;b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2 6;
y=6*- *ptr1/ *ptr2 +30;
printf(“\nAddress of a +%u”,ptr1);
printf(“\nAddress of b %u”,ptr2);
printf(“\na=%d, b=%d”,a,b);
printf(“\nx=%d,y=%d”,x,y);
ptr1=ptr1 + 70;
ptr2= ptr2;
printf(“\na=%d, b=%d,”a,b);
}

Pointers and function:

In a function declaration,the pointer are very much used . Sometimes,only with a


pointer a complex function can be easily represented and success. In a function
definition,the usage of the pointers may be classified into two groups.

1. Call by reference

2. Call by value.

Call by value:

We have seen that there will be a link established between the formal and actual
parameters when a function is invoked. As soon as temporary storage is created
where the value of actual parameters is stored. The formal parameters picks up
its value from storage area the mechanism of data transfer between formal and
actual parameters allows the actual parameters mechanism of data transfer is
referred as call by value. The corresponding formal parameter always represents
a local variable in the called function. The current value of the corresponding
actual parameter becomes the initial value of formal parameter. In the body of
the actual parameter, the value of formal parameter may be changed. In the body
of the subprogram, the value of formal parameter may be changed by assignment
or input statements. This will not change the value of the actual parameters.

/* Include< stdio.h >


void main()
{
int x,y;
x=20;
y=30;
printf(“\n Value of a and b before function call =%d %d”,a,b);
fncn(x,y);
printf(“\n Value of a and b after function call =%d %d”,a,b);
}

fncn(p,q)
int p,q;
{
p=p+p;
q=q+q;
}

Call by Reference:

The address should be pointers,when we pass address to a function the


parameters receiving . By using pointers,the process of calling a function to pass
the address of the variable is known as call by reference. The function which is
called by reference can change the value of the variable used in the call.

/* example of call by reference*?

/* Include< stdio.h >


void main()
{
int x,y;
x=20;
y=30;
printf(“\n Value of a and b before function call =%d %d”,a,b);
fncn(&x,&y); printf(“\n Value of a and b after function call =%d %d”,a,b);
}
fncn(p,q)
int p,q;
{
*p=*p+*p;
*q=*q+*q;
}

Pointer to arrays:

an array is actually very much similar like pointer. We can declare as int *a is an
address,because a[0] the arrays first element as a[0] and *a is also an address the
form of declaration is also equivalent. The difference is pointer can appear on the
left of the assignment operator and it is a is a variable that is lvalue. The array
name cannot appear as the left side of assignment operator and is constant.

/* A program to display the contents of array using pointer*/


main()
{
int a[100];
int i,j,n;
printf(“\nEnter the elements of the array\n”);
scanf(%d,&n);
printf(“Enter the array elements”);
for(I=0;I< n;I++)
scanf(%d,&a[I]);
printf(“Array element are”);
for(ptr=a,ptr< (a+n);ptr++)
printf(“Value of a[%d]=%d stored at address %u”,j+=,*ptr,ptr);
}

Pointers and structures

We know the name of an array stands for address of its zeroth element the same
concept applies for names of arrays of structures. Suppose item is an array
variable of the struct type. Consider the following declaration:

struct products
{
char name[30];
int manufac;
float net;
item[2],*ptr;

this statement ptr as a pointer data objects of type struct products and declares
item as array of two elements, each type struct products.

Pointers on pointer

A pointer contains garbage value until it is initialized. Since compilers cannot


detect the errors may not be known until we execute the program remember that
even if we are able to locate a wrong result,uninitialized or wrongly initialized
pointers it may not provide any evidence for us to suspect problems in pointers.
For example the expressions such as

*ptr++, *p[],(ptr).member

Permalink Leave a Comment
Structure and union in C
February 16, 2008 at 9:08 pm · Filed under 15. Structure and union in C

What is a Structure?

 Structure is a method of packing the data of different types.



 When we require using a collection of different data items of different data
types in that situation we can use a structure.
 A structure is used as a method of handling a group of related data items of
different data types.

Syntax of Using Structure

structure definition:
general format:
struct tag_name
{
data type member1;
data type member2;
….

}

Example of Using Structure:

struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
};

To holds the details of four fields namely title, author pages and price,the
keyword struct declares a structure. These are the members of the structures.
Each member may belong to same or different data type. The tag name can be
used to define the objects that have the tag names structure. The structure we
just declared is not a variable by itself but a template for the structure. We can
declare the structure variables using the tag name any where in the program. For
example the statement, struct lib_books book1,book2,book3; declares the
book1,book2,book3 as variables of type struct lib_books each declaration has four
elements of the structure lib_books. The complete structure declaration might
look like this

The complete structure declaration might look like this

struct lib_books
{
char title[20];
char author[15];
int pages;
float price;
};struct lib_books, book1, book2, book3;

Get the Length of a Node List

The node list is always keeps itself up-to-date. If an element is deleted or added,
in the node list or the XML document, the list is automatically updated.
The node list has a useful property called the length. The length property return
the number of node in a node list.

The following code fragment get the number of <title> elements in


“bookdetails.xml”:

struct lib_books { char title[20]; char author[15]; int pages; float price; }; struct
lib_books, book1, book2, book3;

The following program shows the use of structure

/* Example program for using a structure*/


#include< stdio.h >
void main()
{
int id_no;
char name[20];
char address[20];
char combination[3];
int age;
}newstudent;
printf(”Enter the student information”);
printf(”Now Enter the student id_no”);
scanf(“%d”,&newstudent.id_no);
printf(“Enter the name of the student”);
scanf(“%s”,&new student.name);
printf(“Enter the address of the student”);
scanf(“%s”,&new student.address);printf(“Enter the cmbination of the
student”);
scanf(“%d”,&new student.combination);printf(Enter the age of the student”);
scanf(“%d”,&new student.age);
printf(“Student information\n”);
printf(“student id_number=%d\n”,newstudent.id_no);
printf(“student name=%s\n”,newstudent.name);
printf(“student Address=%s\n”,newstudent.address);
printf(“students combination=%s\n”,newstudent.combination);
printf(“Age of student=%d\n”,newstudent.age);
}

Union:

However the members that we compose a union all share the same storage area
within the computer’s memory where as each member within a structure is
assigned its own unique storage area. Thus unions are used to observe memory.
They are useful for the application involving multiple members. Where values
need not be assigned to all the members at any time. Unions like structure
contain members whose individual data types may differ from one another also.
Like structures union can be declared using the keyword union as follows:

Last example will create a rectangle with rounded corner:

union item
{
int m;
float p;
char c;
}
code;

The notation for accessing a union member that is nested inside a structure
remains the same as for the nested structure. In effect, a union creates a storage
location that can be used by one of its members at a time. When a different
number is assigned to a new value the new value super cedes the previous
member’s value. Unions may be used in all the places where a structure is
allowed.
What is a function?

A function is a block of statement that has a name and it has a property that it is


reusable i.e. it can be executed from as many different points in a C Program as
required.

A function is a self contained block of statements that perform a coherent task of


the same kindFunction helps to groups a number of program statements into a
unit and gives it a name. This unit can be invoked from the other parts of a
program.It is not possible by computer program to handle all the tasks by it self.
Instead its requests other program like entities – called functions in C – to get its
tasks done.
In a C Program,the name of the function is unique and is Global. It meams that a
function can be accessed from any location with in a C Program.when the
function is called,we pass information to the function
called arguments specified.And the function either returns some values to the
point it was called from or returns nothing

Structure of a Function
There are two main parts of the functions. The function header and the function
body.

The following syntax shows th syntax of using function in c:

return_ data_type function name (arguments, arguments)


data _type _declarations of arguments;
{

function body

}
Function Header
int sum(int x, int y)
It has three main parts
1. The function name i.e. sum
2. The parameters of the function enclosed in the paranthesis
3. Return value type of the function i.e. int

Function Body
What ever is written with in { } is the body of the function.
The following example shows the use of functions which prints factorial of a
number:

* Program to calculate a specific factorial number */

#iinclude

void calc_factorial (int); // ANSI function prototype

void calc_factorial (int i)


{

int I, factorial_number = 1;

for (I=1; I <=n; ++i)


factorial_number *= I;
printf(“The factorial of %d is %d\n”, n, factorial_number);
}

int main(void)
{
int number = 0;
printf(“Enter a number\n”);

scanf(“%d”, &number);
calc_factorial (number);

return 0;
}

storage classes.

Storage classes include following categories:

1. auto
2. extern
3. register
4. static.
auto
The auto keyword is used to place the specified variable into the stack area of
memory. In most variable declaration,this is usually implicit one, e.g. int i;
extern
The extern keyword is used to specify variable access the variable of the same
name from some other file. In modular programs,this is very useful for sharing
variables.
register
The register keyword gives suggest to the compiler to place the particular variable
in the fast register memory located directly on the CPU. Most compilers these
days (like gcc) are so smart that suggesting registers could actually make your
program more slower.
static
It is also used to declare the variables to be private to a certain file only when
declared with global variables. static can also be used with functions, making
those functions visible only to file itself.The static keyword is used for extending
the lifetime of a particular variable. The variable remains even after the function
call is long gone (the variable is placed in the alterable area of memory),if you
declare a static variable inside a function,. The static keyword can be overloaded.

 what is a string?
 A string is combination of characters.
 Any set or sequence of characters defined within double quotation symbols
is a constant string.
 In c it is required to do some meaningful operations on the strings

Initializing Strings
The initialization of a string must the following form which is simpler to the one
dimension array

char month1[ ]={‘j’,’a’,’n’,’u’,’a’,’r’,’y’};

The following example shows the use of string:


/*String.c string variable*/
#include < stdio.h >
main()
{
char month[15];
printf (”Enter the string”);
gets (month);
printf (”The string entered is %s”, month);
}
Note:
Character string always terminated by a null character ‘’. A string variable is
always declared as an array & is any valid C variable name. The general form of
declaration of a string variable is

Reading Strings from the terminal:


The function scanf with %s format specification is needed to read the character
string from the terminal itself. The following example shows how to read strings
from the terminals:
char address[15];
scanf(%s,address);

String operations (string.h)


language recognizes that strings are terminated by null character and is a
different class of array by letting us input and output the array as a unit. To array
out many of the string manipulations,C library supports a large number of string
handling functions that can be used such as:
1. Length (number of characters in the string).
2. Concatentation (adding two are more strings)
3. Comparing two strings.
4. Substring (Extract substring from a given string)
5. Copy(copies one string over another)

strlen() function:
This function counts and returns the number of characters in a particular string.
The length always does not include a null character. The syntax of strlen() is as
follows:

n=strlen(string);
Where n is the integer variable which receives the value of length of the string.

The following program shows to find the length of the string using strlen()
function
/*writr a c program to find the length of the string using strlen() function*/
#include < stdio.h >
include < string.h >
void main()
{
char name[100];
int length;
printf(”Enter the string”);
gets(name);
length=strlen(name);
printf(”\nNumber of characters in the string is=%d”,length);
}
strcat() function:
when you combine two strings, you add the characters of one string to the end of
the other string. This process is called as concatenation. The strcat() function is
used to joins 2 strings together. It takes the following form:

strcat(string1,string2)
string1 & string2 are the character arrays. When the function strcat is executed
string2 is appended to the string1. the string at string2 always remains
unchanged.

strcmp function:
In c,you cannot directly compare the value of 2 strings in a condition like
if(string1==string2) Most libraries however contain the function called
strcmp(),which returns a zero if 2 strings are equal, or a non zero number if the
strings are not the same. The syntax of strcmp() is given below:

Strcmp(string1,string2)

strcmpi() function
This function is same as strcmp() which compares 2 strings but not case sensitive.

Strcmp(string1,string2)

strcpy() function:
To assign the characters to a string,C does not allow you directly as in the
statement name=Robert; Instead use the strcpy() function found in most
compilers the syntax of the function is illustrated below.

strcpy(string1,string2);

strlwr () function:
This function converts all characters in a string from uppercase to lowercase
The syntax of the function strlwr is illustrated below

strlwr(string);
strrev() function:
This function reverses the characters in a particular string. The syntax of the
function strrev is illustrated below
strrev(string);

The following program illustrate the use of string functions:


/* Example program to use string functions*/
#include < stdio.h >
#include < string.h >
void main()
{
char s1[20],s2[20],s3[20];
int x,l1,l2,l3;
printf(”Enter the strings”);
scanf(”%s%s”,s1,s2);
x=strcmp(s1,s2);
if(x!=0)
{printf(”\nStrings are not equal\n”);
strcat(s1,s2);
}
else
printf(”\nStrings are equal”);
strcpy(s3,s1);
l1=strlen(s1);
l2=strlen(s2);
l3=strlen(s3);
printf(”\ns1=%s\t length=%d characters\n”,s1,l1);
printf(”\ns2=%s\t length=%d characters\n”,s2,l2);
printf(”\ns3=%s\t length=%d characters\n”,s3,l3);
}

Dynamic Memory alocation is defined as the dynamically allocation of space for


variables at runtime.

· It is wasteful when dealing with array type structures to allocate so much space
when it is declared
Five ANSI Standartd Function Used in Dynamic Memory Allocation
ANSI C provides five standard functions that will help you allocate memory on the
heap which are as follows:
1. sizeof()
2. malloc()
3. calloc()
4. realloc()
5. free()

The following table describe the five different standard functions that helps you
allocate memory dynamically
Functio
Task
n
The sizeof() function returns the memory size of the requested
Sizeof
variable
Allocates memory requests size of bytes and returns a pointer to the
Malloc
Ist byte of allocated space
Allocates space for an array of elements initializes them to zero and
Calloc
returns a pointer to the memory
Free Frees previously allocated space
Realloc Modifies the size of previously allocated space.

sizeof()
The sizeof() function returns the memory size of requested variable. This call
should be used in the conjunction with the calloc() function call, so that only the
necessary memory is allocated, rather than a fixed size. Consider the following,

struct date {
int hour, minute, second;
};

int x;

x = sizeof( struct date );

malloc()
A block mf memory may be allocated using the function called malloc. The malloc
function reserves a block of memory of specified size and return a pointer of type
void. This means that we can assign it to any type of the pointer. It takes the
following form:

ptr=(cast-type*)malloc(byte-size);
ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an
area of memory with the size byte-size. The following is the example of using
malloc function

x=(int*)malloc(100*sizeof(int));

calloc()
Calloc is another memory allocation function that is normally used to request the
multiple blocks of storage each of same size and then sets all bytes to zero. The
general form of calloc is:

ptr=(cast-type*) calloc(n,elem-size);
The above statement allocates contiguous space for n blocks each size of the
elements size bytes. All bytes are initialized to zero and a pointer to the first byte
of allocated region is returned. If there is not enough space a null pointer is also
returned.

realloc()
The memory allocated by using calloc or malloc might be insufficient or excess
sometimes in both the situations we can change the memory size already
allocated with the help of the function called realloc. This process is called the
reallocation of memory. The general statement of reallocation of memory is :

ptr=realloc(ptr,newsize);

free()
Compile time storage of a variable is allocated and released by the system in
accordance with its storage class. With the dynamic runtime allocation, it is our
responsibility to release the space when it is not required at all.When the storage
is limited,the release of storage space becomes important . When we no longer
need the data we stored in a block of memory and we do not intend to use that
block for the storing any other information, Using the free function,we may
release that block of memory for future use.

free(ptr);
ptr is a pointer that has been created by using calloc or malloc.

The following program illustrate the reallocation of memory using realloc() and
malloc()
/*Example program for reallocation*/

#include< stdio.h >


#include< stdlib.h >
define NULL 0
main()
{
char *buffer;
/*Allocating memory*/
if((buffer=(char *) malloc(10))==NULL)
{
printf(“Malloc failed\n”);
exit(1);
}
printf(“Buffer of size %d created \n”,_msize(buffer));
strcpy(buffer,Bangalore);
printf(\nBuffer contains:%s\n,buffer);
/*Reallocation*/
if((buffer=(char *)realloc(buffer,15))==NULL)
{
printf(“Reallocation failed\n”);
exit(1);
}
printf(“\nBuffer size modified”.\n);
printf(“\nBuffer still contains: %s\n”,buffer);
strcpy(buffer,Mysore);
printf(“\nBuffer now contains:%s\n”,buffer);
/*freeing memory*/
free(buffer);
}

What is an array?

* Arrays are collection of similar items (i.e. ints, floats, chars) whose memory is
allocated in a contiguous block of memory.

 Pointers and arrays have a special relationship. To reference memory


locations,arrays use pointers. Therefore, most of the times, array and pointer
references can be used interchangeably.

Declaration of arrays
Arrays must be declared before they are used like any other variable. The general
form of declaration is:

type variable-name[SIZE];
The type specify the type of the elements that will be contained in the array, such
as int,float or char and the size indicate the maximum number of elements that
can be stored inside the array.
The following example illustrate the use of array:
float height[50];
Declares the height to be an array containing the 50 real elements. Any subscripts
0 to 49 are all valid. In C the array elements index or subscript begins with the
number zero. So height [0] refers to first element of the array. (For this reason, it
is easier to think of it as referring to element number zero, rather than as
referring to first element). The declaration int values[10]; would reserve the
enough space for an array called values that could hold up to 10 integers. Refer to
below given picture to conceptualize the reserved storage space.

values[0]
values[1]
values[2]
values[3]
values[4]
values[5]
values[6]
values[7]
values[8]
values[9]

Initialization of arrays:
We can initialize the elements in an array in the same way as the ordinary
variables when they are declared. The general form of initialization off arrays is:

type array_name[size]={list of values};


The values in the list care separated by commas, for example the statement
int number[3]={0,0,0};
The initialization of arrays in c suffers two drawbacks
1. There is no convenient way to initialize only selected element.
2. There is no shortcut method to initialize large number of element
The following program to count the no of positive and negative numbers
/* Program to count the no of positive and negative numbers*/
#include< stdio.h >
void main( )
{
int a[50],n,count_neg=0,count_pos=0,I;
printf(“Enter the size of the array\n”);
scanf(%d,&n);
printf(“Enter the elements of the array\n”);
for I=0;I < n;I++)
scanf(%d,&a[I]);
for(I=0;I < n;I++)
{
if(a[I]< 0)
count_neg++;
else
count_pos++;
} printf(“There are %d negative numbers in the array\n”,count_neg);
printf(“There are %d positive numbers in the array\n”,count_pos);
}

Multi dimensional Arrays:


Often there is a need to store and manipulate two dimensional data structure
such as the matrices & tables. Here array has two subscripts. One subscript
denotes row & the other the column. The declaration of two dimension arrays is
as follows:

data_type array_name[row_size][column_size];
int m[10][20];
The following program illustrate addition two matrices & store the results in the
3rd matrix
/* example program to add two matrices & store the results in the 3rd matrix */
#include< stdio.h >
#include< conio.h >
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q;
clrscr();
printf(“enter the order of the matrix\n”);
scanf(“%d%d”,&p,&q);
if(m==p && n==q)
{
printf(“matrix can be added\n”);
printf(“enter the elements of the matrix a”);
for(i=0;i < m;i++)
for(j=0;j
scanf(%d,&a[i][j]);
printf(“enter the elements of the matrix b”);
for(i=0;i < p;i++)
for(j=0;j 
scanf(%d,&b[i][j]);
printf(“the sum of the matrix a and b is”);
for(i=0;i
for(j=0;j
c[i][j]=a[i][j]+b[i][j];
for(i=0;i < m;i++)
{ for(j=0;j
printf(%d\t,&a[i][j]);
printf(\n);
}

The C Preprocessor is a separate step in the compilation process, but not part of
the compiler.
* C Preprocessor is just a text substitution tool and we’ll refer to the C
Preprocessor as the CPP

The C preprocessor.

 All preprocessor lines always begin with #. This listing is from Weiss pg. 104.
The unconditional directives are as follows:
o #define – Define a preprocessor macro
o #include – Insert a particular header from another file
o #undef – Undefine a preprocessor macro

The conditional directives are as follows:

o #ifndef – If this macro is not defined


o #ifdef – If this macro is defined
o #if – Test if a compile time condition is true
o #elif – #else an #if in one statement
o #else – The alternative for #if
o #endif – End preprocessor conditional

Other directives include:

o ## – Token merge, creates a single token from two adjacent ones


o # – Stringization, replaces a macro parameter with a string constant

Some examples of the above is given below:


#define MAX_ARRAY_LENGTH 20
The above code will tell the CPP to replace instances of MAX_ARRAY_LENGTH
with 20. To increase readability,use #define for constants.

#include
#include “mystring.h”
The above code tells the CPP to get stdio.h from System Libraries and add the text
to this file. The next line tells CPP to get mystring.h from the local directory and
then add the text to the file.

#undef MEANING_OF_LIFE
#define MEANING_OF_LIFE 42
The above code tells the CPP to undefine MEANING_OF_LIFE and define it for 42.

#ifndef IROCK
#define IROCK “You wish!”
#endif
The above code tells the CPP to define IROCK only if IROCK isn’t defined already.

#ifdef DEBUG
/* Your debugging statements here */
#endif
Thed above code tells the CPP to do the following statements if DEBUG is
defined.If you pass the -DDEBUG flag to gcc,this is useful .

Permalink Leave a Comment
The C operators fall into the following categories:

 Postfix operators, which follow a single operand only.


 Unary prefix operators, which precede with a single operand.
 Binary operators, which take two operands and perform a variety of logical
and arithmetic 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 only.
 Assignment operators, which only assign a value to a variable.
 The comma operator, which gives guarantees left-to-right evaluation of
comma-separated expressions.

To create more complex expressions,variables and constants can be used in


conjunction with C operators. The following tables describes different operators
available in c
Operator Example Description/Meaning
() f() Function call
[] a[10] Array reference
-> A td <> Structure and union member selection
. s.a Structure and union member selection
+ [unary] +a Value of a
- [unary] -a Negative of a
* [unary] *a Reference to object at address a
& [unary] &a Address of a
~ ~a One’s complement of a
++ [prefix] ++a The value of a after increment
++ [postfix] a++ The value of a before increment
- – [prefix] -a The value of a after decrement
- – [postfix] a- The value of a before decrement
Sizeof sizeof (t1) Size in bytes of object with type t1
Sizeof sizeof e Size in bytes of object having the type of expression e
a+b a plus b
+ [binary]
a–b a minus b
- [binary]
a*b a times b
* [binary]
a/b a divided by b
/%
a%b Remainder of a/b
>> a >> b a, right-shifted b bits
<< a << b a, left-shifted b bits
< a<b 1 if a < b; 0 otherwise
> a>b 1 if a > b; 0 otherwise
<= a <= b 1 if a <= b; 0 otherwise
>= a >= b 1 if a >= b; 0 otherwise
== a == b 1 if a equal to b; 0 otherwise
!= a != b 1 if a not equal to b; 0 otherwise
& [binary] a&b Bitwise AND of a and b
| a|b Bitwise OR of a and b
^ a^b Bitwise XOR (exclusive OR) of a and b
&& a && b Logical AND of a and b (yields 0 or 1)
|| a || b Logical OR of a and b (yields 0 or 1)
! !a Logical NOT of a (yields 0 or 1)
Expression e1 if a is nonzero;
?: a ? e1 : e2
Expression e2 if a is zero
= a=b a, after b is assigned to it
+= a += b a plus b (assigned to a)
-= a -= b a minus b (assigned to a)
*= a *= b a times b (assigned to a)
/= a /= b a divided by b (assigned to a)
%= a %= b Remainder of a/b (assigned to a)
>>= a >>= b a, right-shifted b bits (assigned to a)
<<= a <<= b a, left-shifted b bits (assigned to a)
&= a &= b a AND b (assigned to a)
|= a |= b a OR b (assigned to a)
^= a ^= b a XOR b (assigned to a)
, e1,e2 e2 (e1 evaluated first)

Precedence of C Operators
Category Operator Associativity
Postfix () [] -> . ++ – - Left to right
Unary + – ! ~ ++ – - (type) * & sizeof Right to left
Multiplicative */% Left to right
Additive +– Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

The standard Input Output File.

To perform,input and output to files or the terminal,UNIX supplies a standard


package.To use them,this contains most of the functions which will be introduced
in this section,along with definitions of the datatypes required.Your program must
include these definitions by adding the line to use these facilities.
#include near start of the program file. If you do not do this, the compiler may
complain about undefined datatypes or functions.

Character Input / Output


If you will not press the return key then they’ll not start reading any input, and
they’ll not print characters on the terminal until there is a whole line to be
printed. This is the lowest level of output and input. It provides very precise
control, but is usually too fiddly to be useful also. Most computers perform
buffering of inputs and outputs. These include :
1. getchar
2. putchar

getchar
getchar always returns the next character of keyboard input as an int. The EOF
(end of file) is returned,if there is an error . It is usual to compare this value
against EOF before using it. So error conditions will not be handled correctly,if the
return value is stored in a char, it will never be equal to EOF.
The following program is used to count the number of characters read until an
EOF is encountered. EOF can be generated by typing Control – d.
#include

main()
{ int ch, i = 0;

while((ch = getchar()) != EOF)


i ++;
printf(“%d\n”, i);
}

putchar
putchar puts its character argument on the standard output (usually the screen).
The following example program converts any typed input into capital letters.It
applies the function toupper from the character conversion library ctype.h to
each character in turn to do this.

#include /* For definition of toupper */


#include /* For definition of getchar, putchar, EOF */

main()
{ int ch;
while((ch = getchar()) != EOF)
putchar(toupper(ch));
}

Formatted Input / Output


These includes following:
1. printf
2. scanf

printf
This offers more structured output than the putchar. Its arguments are, in order;
a control string, which controls what get printed, followed by a list of values to be
substituted for entries in the control string. The prototype for the printf() is:

Control String Entry What Gets Printed

%d Decimal Integer

%f Floating Point Value

%c Single Character

%s Character String

int printf(const char *format, …);


To print,printf takes in a formatting string and the actual variables . An example of
printf is:
int x = 5;
char str[] = “abc”;
char c = ‘z’;
float pi = 3.14;

printf(“\t%d %s %f %s %c\n”, x, str, pi, “WOW”, c);

With the use of the formatting line,you can format the output.You can change
how the particular variable is placed in output,by modifying the conversion
specification, . For example

printf(“%10.4d”, x);
The . allows for the precision.To floats as well,this can be applied.The number 5 is
on the tenth spacing as the number 10 puts 0005 over 10 spaces. You can also
add – and + right after % to make the number explicitly output as +0005. Note
that the value of x does not actually change. In other words,you will not get
output using %-10.4d will not output -0005. %e is useful for outputting floats
using the scientific notation. %le for doubles and %Le for the long doubles.
To grab things from input,scanf() is used. Beware though, scanf isn’t greatest
function that C has to offer. Some people brush off the scanf as a broken function
that shouldn’t be used often. The prototype for scanf is:
Last example will create a rectangle with rounded corner:

int scanf( const char *format, …);


To read of data from the keyboard,scanf allows formatted . Like printf it has a
control string,followed by the list of items to be read. However scanf wants to
know the address of items to be read, since it is a function which will change that
value. Therefore the names of variables are preceeded by the & sign. Character
strings are an exception to this. Since a string is already a character pointer, we
give the names of the string variables unmodified by a leading &. Control string
entries which match values to be read are preceeded by the percentage sign in a
similar way to their printf equivalent. Looks similar to printf, but doesn’t
completely behave like the printf does. Take the example:
scanf(“%d”, x);
For grabbing things from input. Beware though, scanf isn’t the greatest function
that C has to offer,scanf() is used. The following is the example which shows the
use of scanf:
int x, args;

for ( ; ; ) {
printf(“Enter an integer bub: “);
if (( args = scanf(“%d”, &x)) == 0) {
printf(“Error: not an integer\n”);
continue;
} else {
if (args == 1)
printf(“Read in %d\n”, x);
else
break;
}
}
When should the volatile modifier be used ?

The volatile modifier is a directive to the compiler’s optimizer that operations


involving this variable should not be optimized in certain ways. There are two
special cases in which use of the volatile modifier is desirable. The first case
involves memory-mapped hardware (a device such as a graphics adaptor that
appears to the computer’s hardware as if it were part of the computer’s
memory), and the second involves shared memory (memory used by two or more
programs running simultaneously).

Most computers have a set of registers that can be accessed faster than the
computer’s main memory. A good compiler will perform a kind of optimization
called redundant load and store removal. The compiler looks for places in the
code where it can either remove an instruction to load data from memory
because the value is already in a register, or remove an instruction to store data
to memory because the value can stay in a register until it is changed again
anyway. 
If a variable is a pointer to something other than normal memory, such as
memory-mapped ports on a peripheral, redundant load and store optimizations
might be detrimental. For instance, here’s a piece of code that might be used to
time some operation:

time_t time_addition(volatile const struct timer *t, int a)


{
int n;
int x;
time_t then;
x = 0;
then = t->value;
for (n = 0; n < 1000; n++)
{
x = x + a;
}
return t->value - then;
}

In this code, the variable t-> value is actually a hardware counter that is being
incremented as time passes. The function adds the value of a to x 1000 times, and
it returns the amount the timer was incremented by while the 1000 additions
were being performed. Without the volatile modifier, a clever optimizer might
assume that the value of t does not change during the execution of the function,
because there is no statement that explicitly changes it. In that case, there’s no
need to read it from memory a second time and subtract it, because the answer
will always be 0.

The compiler might therefore optimize the function by making it always return 0. 
If a variable points to data in shared memory, you also don’t want the compiler to
perform redundant load and store optimizations. Shared memory is normally
used to enable two programs to communicate with each other by having one
program store data in the shared portion of memory and the other program read
the same portion of memory. If the compiler optimizes away a load or store of
shared memory, communication between the two programs will be affected.

1. In 1972, C was developed at Bell Laboratories by Dennis Ritchie.


2. C is a simple programming language with a relatively simple to understand
syntax and few keywords.

3. C is useless.C itself has no input/output commands, doesn’t have support


for strings as a fundamental data type. There is no useful math functions built
in.

4. C requires the use of libraries as C is useless by itself. This increases the


complexity of the C.The use of ANSI libraries and other methods,the issue of
standard libraries is resolved.

C Programming :: A Quick Hellow World Program


Let’s give a simple program that prints out “Hello World” to standard out. We’ll
call our program as hello.c.

#includemain() {
printf(”Hello, world!\n”);
return 0;
}

Explanation of The Above Code:


 #include -This line tells the compiler to include this header file for
compilation.
o What is header file?They contain prototypes and other
compiler/pre-processor directive.Prototypes are also called the basic
abstract function definitions.
o Some common header files are stdio.h,stdlib.h, unistd.h and math.h.
 main()- This is a function, in particular it is the main block.
 { } – These curly braces are equivalent to the stating that “block begin” and
“block end”.These can be used at many places,such as switch and if
statement.
 printf() – This is the actual print statement which is used in our c program
fraquently.we have header file stdio.h! But what it does? How it is defined?
 return 0-What is this? Who knows what is this

Seems like trying to figure out all this is just way too confusing.

 Then the return 0 statement. Seems like we are trying to give something
back, and it gives the result as an integer. Maybe if we modified our main
function definition: int main() ,now we are saying that our main function will
be returning an integer!So,you should always explicitly declare the return
type on the function.
 Let us add #include to our includes. Let’s change our original return
statement to return EXIT_SUCCESS;. Now it makes sense!
 printf always returns an int. The main pages say that printf returns the
number of characters printed.It is good programming practice to check for
return values. It will not only make your program more readable, but at the
end it will make your programs less error prone. But we don’t really need it in
this particular case.So we cast the function’s return to (void). fprintf,exit and
fflush are the only functions where you should do this.
 What about the documentation? We should probably document some of
our code so that other people can understand what we are doing. Comments
in the C89 standard are noted by this: /* */. The comment always begins with
/* and ends with */.

An Improved Code of The Above Example


#include #include/* Main Function
* Purpose: Controls our program, prints Hello, World!
* Input: None
* Output: Returns Exit Status
*/

int main() {
(void)printf(”Hello, world!\n”);
return EXIT_SUCCESS;
}

Note:The KEY POINT of this whole introduction is to show you the fundamental
difference between understandability and correctness. If you lose
understandability in an attempt to gain correctness, you will lose at the end.
Always place the understandability as a priority ABOVE correctness. If a program
is more understandable in the end,the chances it can be fixed correctly will be
much higher. It is recommend that you should always document your program.
You stand less of a chance of screwing up your program later,if you try to make
your program itself more understandable.

The advantages of C
In other words,for writing anything from small programs for personal amusement
to complex industrial applications,C is one of a large number of high-level
languages designed for general-purpose programming.
C has many advantages:

 Before C,machine-language programmers criticized high-level languages


because,with their black box approach,they shielded the user from the
working details of all its facilities and the computer. To give access to any
level of the computer down to raw machine language,however, C was
designed and because of this, it is perhaps the most flexible high-level
language.
 To organize programs in a clear,easy,logical way,C has features that allow
the programmer.For example,C allows meaningful names for variables
without any loss of efficiency, yet it gives a complete freedom of
programming style,a set of flexible commands for performing tasks
repetitively (for, while,do) and including flexible ways of making decisions.
 C is also succinct. It permits the creation of tidy and compact programs.
This feature can be a mixed blessing, however, and the C programmer must
balance readability and simplicity.
 C allows commands that are invalid in some other languages. This is no
defect, but a powerful freedom which, when used with caution, makes many
things easily possible. It does mean that there are concealed difficulties in C,
but if you write thoughtfully and carefully, you can create fast, efficient
programs.
 With C, you can use every resource of your computer offers. C tries to link
closely with the local environment, providing facilities for gaining access to
common peripherals like printers and disk drives.

The C Compilation Model

Creating, Compiling and Running Your Program


Creating the program
First create a file containing the complete program, such as the above example.
You can use any ordinary editor to create the file. One such editor
is texteditwhich is available on most UNIX systems.
The filename must have extension “.c” (full stop, lower case c), e.g.
myprog.c orprogtest.c. The contents must have to obey C syntax. For example,
they might be as in the above example,starting with the line /* /* end of the
program */.

Compilation
There are many C compilers are present around. The cc is being the default Sun
compiler. The GNU C compiler gcc is popular and also available for many
platforms. PC users may also be familiar with Borland bcc compiler.
There are also C++ compilers which are usually denoted by CC (note upper case
CC.For example Sun provides GNU and CCGCC. The GNU compiler is also denoted
by the command g++
Other C/C++ compilers also exist. All the above compilers operate in essentially
the share many common command line options and same manner. However,
thebest source of each compiler is through online manual pages of your
system: e.g.man cc.
In the basic discussions of compiler operation,for the sake of compactness,we will
simply refer to the cc compiler — other compilers can simply be substituted in
place of cc until and unless otherwise stated.
Your program simply invoke the command cc to Compile . The command must be
followed by the name of the (C) program you wish to compile it.
The compilation command is:
cc program.c
where program.c is name of the file.
If there are obvious errors in your program (such as mistypings, misspelling one of
the key words or omitting a semi-colon), the compiler will detect it and report
them.
It may possible that the compiler cannot detect logical errors.
If the compiler option -o is used : the file listed after the -oor when the compiler
has successfully digested your program, the compiled version, or executable, is
left in a file called a.out
It is convenient to use a -o and filename in the compilation as in
cc -o program program.c
which puts the compiled program into the file program ( any file you name
following the “-o” argument) instead of putting it in the file a.out .

Running the program


The next stage is to run your executable program.You simply type the name of the
file containing it, in this case program (or a.out),to run an executable in UNIX.
This executes your program able to print any results to the screen. At this stage
there may be run-time errors, such as it may become evident that the program
has produced incorrect output or division by zero.
If so, you must return to edit your program source, and compile it again, and run
it again.

C is a High Level Language


C is also called as a high-level language. To give a list of instructions (a computer
program) to a computer,the high-level computer language is used. The native
language of the computer is a stream of numbers called machine level language.
As you might expect, the action resulting from a single machine language
instruction is very primitive, and many thousands of them can be required to do
something like substantial. A high-level language provides a set of instructions
you can recombine creatively and give to the imaginary black boxe of the
computer. The high-level language software will then translate these high-level
instructions into the low-level machine language instructions

Characteristics of C
We briefly list some of C’s characteristics that have lead to its popularity as a
programming language and define the language. Naturally we will be studying
many of these aspects throughout our tutorial.

 Extensive use of function calls


 Small size
 Loose typing — unlike PASCAL
 Structured language
 Low level (BitWise) programming readily available
 Pointer implementation – extensive use of pointers for memory, array,
structures and functions.

C has now become a widely used professional language for various reasons.

 It has high-level constructs.


 It produces efficient programs.
 It can handle low-level activities.
 It can be compiled on a variety of computers.

The main drawback of c is that it has poor error detection which can make it off
putting to the beginner. However diligence in this matter can pay off handsomely
since having learned the rules of the C we can break them. Not all languages allow
this. This if done carefully and properly leads to the power of C programming.

C Program Structure
A C program basically has the following form:

 Preprocessor Commands
 Function prototypes — declare function types and variables passed to
function.
 Type definitions
 Variables
 Functions

We must have a main() function


C assumes that function returns an integer type,if the type definition is omitted.
NOTE: This can be a source of the problems in a program

/* Sample program */main()


{
printf( “I Like C \n” );
exit ( 0 );
}
NOTE:
1. printf is a standard C function — called from main.
2. C requires a semicolon at the end of the every statement.
3. \n signifies newline. Formatted output — more later.
4. exit() is also a standard function that causes the program to terminate. Strictly
speaking it is not needed here as it is the last line of main() and the program will
terminate anyway.