Showing posts with label C Language. Show all posts
Showing posts with label C Language. Show all posts

Sunday, 2 September 2012

C - Storage Classes

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

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. autocan only be used within functions, i.e. local variables. 

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  Miles;
        }
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.

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 is 6 and count is 9
   i is 7 and count is 8
   i is 8 and count is 7
   i is 9 and count is 6
   i is 10 and count is 5
   i is 11 and count is 4
   i is 12 and count is 3
   i is 13 and count is 2
   i is 14 and count is 1
   i is 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 between defintion 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 ofthis 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.

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 understandingextern 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

C - Variable Types


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

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 ablock.
·         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 will generate following output
   i is 5
   i is 100
   i is 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;

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
Initialser
int
0
char
'\0'
float
0
pointer
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.

Saturday, 1 September 2012

C - Reserved Keywords


C - Reserved Keywords

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 function section 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.

Note the followings

·         C is a case sensitive programming language. It means in C printfand 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.

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

C - Program Structure


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 Programwill 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 function section 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.

Note the followings

  • C is a case sensitive programming language. It means in C printf andPrintf 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.

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

C - Basic Introduction

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 Eqquipment 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.

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

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

C Program File

All the C programs are writen into text files with extension ".c" for examplehello.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.

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.

What Are These? | Blog Translate Gadget

Cookies

Animated Social Gadget - Blogger And Wordpress Tips