Sunday, August 19, 2018

Components of C



The components of C are as shown in figure. They are divided into six categories. Learning C language means learning about them. Following chapters discuss some of these components in details.
A programming language is composed of a bunch of words combined. A computer program is the formatting and use of these words in an organized manner. These bunches of words are known as tokens. A token is the smallest element of a program that is meaningful to the compiler.
The syntax is nothing but rules imposed by language or compiler on code and semantics are meanings it takes out from it.
Words and phrases are used to make sentences and sentences are used to make paragraphs.
In the same way, whitespace, keywords, literals, and identifiers are combined to make expressions and statements. These in turn are combined to make a program.

Statements & Expressions

Expressions are like phrases. They are snippets of code made up of keywords.
For example, the following are simple expressions:
PI = 3.14159
PI * radius * radius
Statements are like sentences. They complete a single thought. A statement generally ends with a punctuation character—a semicolon (;).For example, the following are simple expressions:
PI = 3.14159;
result = PI * radius * radius;

Special Symbols

The following special symbols are used in C having some special meaning and thus, cannot be used for some other purpose.[] () {}, ; * = #

Brackets [ ]

The opening and closing brackets are used as array element reference. These indicate single and multidimensional subscripts.
The brackets are used with arrays and examples are as follows:
/* in variable declaration */
int x [3] ; /* 3 element array of type integer */

char *name [3] = { “Tom”, “Dick” , “Harry” } ;

for (int i = 0 ; i < 2 ; i++ )
  printf (“ Name: %s” , name [i] );

Parentheses ( )

The special symbols are used to indicate function calls and function’s parameters.
The parentheses are used with functions and examples are as follows:
/* in function declaration */
int add ( int x , int y ) ;

/* at function call */
result = add ( 3, 3 ) ;

/* at function definition */
int add ( int x , int y )
{return ( x + Y ); }

/* at casting one number to another */
int k; float pi=3.142;
k = (int) pi * 2 ;


Braces { }

These opening and ending curly braces marks the start and end of a block of code containing more than one executable statement.
The braces are used with code blocks and at array elements initialization and examples are as follows:
/* at function definition */
int add ( int x , int y )
{
return ( x + Y );
}

/* at array element initialization */
char *name [3] = { “Tom”, “Dick” , “Harry” } ;
See the Code Blocks and Scope section for further details.

Comma ,

It is used to separate more than one statements like for separating parameters in function calls.
The comma is used with separation of elements and examples are as follows:
/* at array element initialization */
int rollNos [3] = { 111, 112 , 113 } ;

/* at function declaration */
int add ( int x , int y )

Semi-colon ;

It is an operator that essentially invokes something called an initialization list.
As program is made of many statements, expressions or control structures it is necessary to separate them from one another. For this separation purpose, each statement is terminating with semi-colon. 
So while declaring, initializing functions, variables, constants, or calling functions or writing expressions semi-colon is use at the end of statement.
The statement terminator semi-colon symbol examples are as follows:
/* in variable declaration */
in x ; char ch = ‘M’ ; float PI = 3142 ;
/* in expressions or statements */
k = i * j ;  x = 1971 ;
/* in function declaration */
int add ( int x , int y ) ; 

Empty Statement or Null Statement

The semi-colon by itself constitutes a valid statement, the null statement. Null statement is often very handy, and we will quite frequently have occasion to use them. It itself does nothing, no expressions to execute hence called Empty statement on its own line.
Example code line for this type is as follows:
/* Null Statement showing code */
while ( ans == ‘ y ’ )
 ;   /* do nothing!*/

Asterisk *

It is used to create pointer variable.
The asterisk is used with pointers and examples are as follows:
/* in pointer of string type declaration */
char *name [3] = { “Tom”, “Dick” , “Harry” } ;

Assignment Operator =                                                            

It is used to assign values.
The assignment operator is used with assign values and examples are as follows:
/* at assigning three string variables to char array */
char *name [3] = { “Tom”, “Dick” , “Harry” } ;



/* at assigning variables with operation to another variable */
z = x + y ;

Pre-processor #

The preprocessor is a macro processor that is used automatically by the compiler to transform your program before actual compilation.
The pre-processor is used with macro processor and examples are as follows:
/* at include section: to include header file */
#include < stdio.h >
#include “add.h”

/* to define something */
#define PI     3.142

Code Blocks and Scope

While writing codes one needs to group them according to their need. In such situations flower brackets are used. They limit the scope of any variable within the two flower brackets. If declarations of variables, constants and functions are not within any flower brackets they are treated as global one and can be accessed throughout source file easily without any restriction.
int i, j ,result;
i=3; j = 4;
{
result = i + j ;
printf ( “result = %d “, result);
/* result = 7 */
int k=125;
printf ( “k = %d “, k);
/* k = 125 */
}
i=15; j = 27;
{
float k=125.5;
printf ( “k = %f “, k);
/* k = 125.5 */
}
In the above code segments, I & j are global variables and can be accessed in any code block within source file. Whereas k is local variable and can be accessed within code block it is declared is possible.

Reserved Words or Keywords

Every C program is composed of many keywords or reserved words and they make up a language. These keywords have a specific meaning when you program in C. This tutorial also discusses usage of these keywords here and there. Because all these words have a special meaning, they are reserved. You cannot use them for your own use. In simple terms, programmer cannot use such words to name variables or constant names or function names in his program.
This is a list of reserved keywords in C. Since they are used by the language, these keywords are not available for re-definition.
The most common keywords that begin with an underscore are generally used through their convenience macros:

White Space or Free form code

The blank spaces put into a listing are called whitespace. Whitespace can consist of spaces, tabs, line feeds, and carriage returns. [Note that escape sequences provide such facility to programmer to hard code in his program].The compiler almost always ignores whitespace. Because of this, you can add as many spaces, tabs, or line feeds as you want. For example,
printf ( “Hello World!\n Hello Universe!”);
/* above printf() function prints below two lines on screen for user*/
Hello World!
Hello Universe!
printf ( “Hello World!\t Hello Universe!”);
/*above printf() function prints two strings with tab separate on screen*/
Hello World!         Hello Universe!
The importance of white space while coding c programs is evident by seeing below expression statement example.
int result=20;
This is a well-formatted line with a single space between items. This line could have had additional spaces:
int result = 20 ;
This line with extra spaces executes the same way as the original. In fact, when the program is run through the C compiler, the extra whitespace is removed. You could also format this code across multiple lines:
int
result
=
20
;
Although this is not very readable, it still works.

Note that no space is inserted whenever it is necessary may leads to error in program. For example,
intresult=20;
above expression is wrong as int and result are two different entity and no space is provided while declaring leads to error.
Because whitespace is ignored in general usage, you should make liberal use of it to help format your code and make it readable.
The exception to the compiler ignoring whitespace has to do with the use of text within quotation marks. When you use text within double quotes, whitespace is important because the text is to be used exactly as presented. Text has been used within quotation marks with the listings you have seen so far. This text is written exactly as it is presented between the quotation marks. For example,
printf(“ Hello! whats…   your name? let me recall..”);
/*prints as it is, with spaces*/
 Hello! whats…   your name? let me recall..
Tip Use whitespace to make your code easier to read.
Note about free form language, as C is one such language it does not care where you put braces or start the line of instructions. For example,
main()
{
int x, y, z=0;
z = 3 + 2;
printf( “Hello World! result is %d”, z);
}
is written also as below, although is less readable.
main(){int x, y, z=0;z = 3 + 2;printf( “Hello World! result is %d”, z);}
Another example for bad coding but legal program lines is as follows:
printf ( “This is first line”);
printf      (“This is second line”);
printf        (“This is third line”)                ;
The statements in C may be any length and may begin in any column. Each statement may extend over several lines, as long as any included strings are not broken.
Note: This is not true with directives such as including library files using #include directive, defining constants using #define etc.

Comments Or Annotating Programs

Comments are a way of inserting remarks and reminders into code without affecting its behavior. Since comments are only read by other humans, you can put anything you wish to in a comment, but it is better to be informative than humorous.
The compiler ignores comments, treating them as though they were whitespace (blank characters, such as spaces, tabs, or carriage returns), and they are consequently ignored.
During compilation, comments are simply stripped out of the code, so programs can contain any number of comments without losing speed.
Because a comment is treated as whitespace, it can be placed anywhere whitespace is valid, even in the middle of a statement. (Such a practice can make your code difficult to read, however.)
Any text sandwiched between `/*' and `*/' in C code is a comment.
Examples of comments:
/* declaring integer type variables*/
int x , y , z;

z = 0 ; /*Initializing variable z */

z = x + /*between add operation */ y;

/*****************************
* add() – function adds two integers
* takes two parameters:
* int x and int y
* returns integer type data
******************************/
int add(int x, int y)
{return ( x+y );}

Coding guidelines

Even though C is free form language certain coding guidelines should be follow in programming as is necessary for code management. The basic conventions are:
·         Put the main() function on its own line.
·         Put the opening and closing braces on their own lines.
·         Indent the code blocks within braces so that reading will be easy.
·         The include statements start at top of file and on first column.
The below code sample shows such program segment.

#include <stdio.h>

int main(void)
{
printf(“Hello world!”);
....
if ( a > b)
  {
  printf(“a is big”);
  i++;
  }
else
  printf(“b is big”);

}

C language library list

The core of the C language is small and simple, but special functionality is provided in the form of external libraries of ready-made functions. Standardized libraries make C code extremely portable, or easy to compile on many different computers.
Libraries are files of ready-compiled code that the compiler merges, or links, with a C program during compilation. For example, there are libraries of mathematical functions, string handling functions, and input/output functions. Indeed, most of the facilities C offers are provided as libraries.
Some libraries are provided for you. You can also make your own, but to do so, you will need to know how GNU builds libraries. Most C programs include at least one library. You need to ensure both that the library is linked to your program and that its header files are included in your program.
In simple term, C does not have any command for displaying information on screen or get information from keyboard. Such frequently needed tasks are written in reusable code files and supplied with compiler as in-built library functions. The user has to add just library function’s declaration file, called header file in his code by writing #include <> directive at the start of code. Then the compiler parses the code, adds header file contents to source code and links pre-compiled library code of the header file from standard library folder. [Refer Basic Program code segment which prints Hello world! to the user on console]
Pre-processing is a phase of compilation that is performed prior to the analysis of the program text. The pre-processor directives differ from statements in two ways: one, they must begin in the first column, with no spaces between the # and the include keyword; and two, they are not terminated by a semicolon.
The #include directive causes the inclusion of external text__ in this case the file stdio.h__ in your source program before the actual compilation proceeds.
Header File name
Purpose
assert.h
program diagnostics/debugging macro
bios.h
function to link to system BIOS [Basic Input/Output System] routine
ctype.h
character testing
dir.h
used in working directories
fcntl.h
low level file routines
limits.h
integral type sizes
math.h
math functions, such as sin(),cos()…
process.h
support for spawn and exec functions
setjmp.h
Non-local flow control jumps
signal.h
exceptional condition signals
stdarg.h
standard argument declaration
stdio.h
standard I/O macros and functions
stdlib.h
standard functions such as malloc, rand
string.h
string functions/operations
time.h
date and time utilities
values.h
constants compatible with UNIX system V
The standard libraries are also called as predefined functions, built-in functions, or library functions. Most of the C compilers support the following standard library facilities.
·         Mathematical operations
·         Operation on strings
·         Operation on characters
·         Storage allocations procedures
·         Input-output operations

Errors

Errors are nothing but mistakes done by programmer while coding any program or wrong user input by user while using the program.
While compiling compiler checks for syntax errors and reports it to programmer for correction, and until all errors are not cleared program will not compile. Since compiler sometimes reports huge number of errors for single syntax error, it is advisable to clear first encountered error and recompile code to check for further errors. Sample compiler errors are typing whlie instead of while or int x = 8.2 assigning float number to integer type variable, semi-colon or brace is missed etc.
As name implies, Run-time errors are errors occur at execution time of any program. It may be due to wrong user input or malfunctioning of program due to library mismatch etc.
Note for programmer: C is case-sensitive language
Like Linux operating system, C is also case sensitive language. It differ menu from Menu that means c considers them as two different names.
Note for programmer: C is typed language
C is a typed language, and it means data is to be typed or declared before using them. There are many in-built data types which are only allowed in c programs. Care should be taken while defining or initializing data types, with same type is advised. For example integer type variable is to be initialized with integer type values only, not any float type or character type data.  


Previous Page Main Contents Next Page

No comments:

Post a Comment