Friday, 15 March 2013

Ellipsis(...) Symbol in C

A different type of argument passing used in C which we is not very popular but very important to know.It is also used by printf and scanf function because we can pass variable no of variables in printf and scanf.We can see how we use this elipsis symbol in our program.So here is the snapshot of my program:

The output of this program will be 11 and 18 respectively.


Wednesday, 13 March 2013

Character set encoding

Character set:-When we write a program, we express source files as text lines containing characters from the source character set.When a program executes in the target environment ,it uses characters from the target character set.These character sets are related ,but need not have the same encoding or all the same members .
               Every character set contains  a distinct code value for each character in the basic C character set.A character set can also contain additional characters with other code values .For example:

  •    The character constant 'x' becomes the value of the code for the character corresponding to x in the target character set.
  • The string literal "xyz" becomes a sequence of character constants stored in successive bytes of memory,followed by a byte containing  the value zero{'x','y','z','\0'}. 
Character encoding:-A character encoding system consists of a code that pairs each character from a given repertoire with something else such as bit pattern,sequence of natural numbers,octets or electrical pulses, in order to facilitate the transmission of data through telecommunication networks or for data storage .Common example of character encoding systems include Morse code,the Baudot code ,Ascii and Unicode.
Here are some important terms used in character set encoding :-

ASCII:-Ascii stands for American standard code for information interchange .It is a character encoding scheme originally based on English alphabet.Ascii codes represent text in computers,communication equipment and other devices that uses text.Most modern character encoding scheme is based on Ascii though they support many additional characters.Ascii developed from telegraphic codes.Its first commercial use was a seven-bit teleprinter code.Ascii includes definitions for  128 characters: 33 are non printing control character that affects how text and space are processed and 95 printable chars including space which is considered an invisible graphics.Extended ASCII comprises 256 code point in the range 0(hex) to ff(hex)

EBCDIC:-EBCDIC stands for extended binary coded decimal interchange code is an 8-bit chatracter encoding use mainly on IBM mainframe  and IBM midrange computer operating system.It is developed before ASCII. EBCDIC has no technical advantage compared to ASCII based webpages .

Unicode:-Unicode is a computer industry standard for the consistent encoding,representation and handling of text expressed .It is a worldwide character encoding standard that provides a unique number to represent each character used in modern computing ,including technical symbols and special characters used in publishing.



UNICODE
Universal character name                                   ISO/IEC 10646 short name
where N is a hexadecimal digit
\UNNNNNNNN                                                   NNNNNNNN
\uNNNN 0000NNNN

. UTF literals
Syntax                                                            Explanation
u'character'                                                   Denotes a UTF-16 character.
u"character-sequence"                                Denotes an array of UTF-16 characters.
U'character' Denotes a UTF-32 character.
U"character-sequence"                               Denotes an array of UTF-32 characters.


examples:

u'\u1234'

u"\u1234\u8189"

U'\U12345678'

U"\U12345678\U43332233"




                 Unicode comprises 1,114,112 code points in the range 0(hex) to 10FFFF(hex) code points in the range.The Unicode code space is divided into seventeen planes(the basic multilingual plane and 16 supplementary planes),each with 65,536=(2^26) code points.Thus the total size of the Unicode code spaces 17*65,536=1,114,112.  Unicode is required by modern standard such as XML and java scripts.It is supported by many operating systems all modern browsers.It has two mapping metods:-

1)UTF:-It stands for unicode transformation format.For UTF encoding the number in the names of encoding indicate the no of bits in one code value.
  a)UTF-8:-UTF-8 is a variable width encoding that can represent every character in  the Unicode character set.It was designed for backward compatibility with ASCII and to avoid the complications of endiannes and byte order marks in UTF-16 and  UTF-32.UTF-8 has become dominant character encoding for the world wide web accounting for more than half of all webpages.UTF-8 is also increasingly  being used as the the default  character encoding in operating systems, programming language,APIs and software application.
 b)UTF-16:-   UTF-16 (16-bit unicode transformation format)is a character encoding for encoding 1,112,064 numbers in the Unicode color space 0 to 0x10FFFF.It produces a variable-length result either one or two 16-bit code units per code-unit.
c)UTF-32:-UTf-32 is a protocol to encode Unicode characters that uses exactly 32 bits per Unicode code point .All other Unicode information formats use variable -length encodings.The main advantage of UTF-32 versus variable-length encodings ,is that unicode code points are directly indexable .
d)UTF-EBCDIC:-UTF-EBCDIC  is a character encoding used to represent Unicode characters .It is meant to be EBCDIC -friendly .

2)UCS:-The Universal character set (UCS) is standard set of characters upon which many character encoding are based.The UCS contains  one hundred thousand abstract characters,each identified by an unambiguous name and an integer number called its endpionts.Characters (letters,numbers ,symbol, ideograms ,logograms etc.) from the many languages ,scripts and traditions of the world are represented in the UCS with unique cods points .It has two forms:-

a)UCS-2:-UCS-2 is similar to the UTF-16.

b)UCS-4:-It is similar to the UTF-32.

Multibyte Character Encoding:-Multibyte character encoding uses varying number of bytes to encode different characters.Multibyte encodings are usually the result of a need to increase the number of characters which can be encoded without  backward compatibilty with an existing constraint .

Wide-character:- A wide character is a computer character datatype that generally has a size greater than the traditional 8-bit character .The increase datatype size allows for the use of larger codec character sets.A wide character refers to the size of the datatype in memory .It does not state how each value in a character
set is defined .Those values are instead defined using characters sets with UCS and Unicode simply being two common character sets that contain more characters than an 8-bit value would allow.

We need to know answers of some questions which are necessary to know us:-

1) What is the default value of character encoding in visual studio.?
Ans:-character set-Use Multi-Byte Character Set
2)What are the possible values of character encoding in VS ?
Ans:-1)Use Multi-Byte Character Set
        2)Not Set
        3)Use Unicode Character Set
3)How can you change this value in VS?
Ans:-We can change this value with following procedure:-
        a)Go to the project properties in visual studio.
        b)There is a option for character set in project defaults where "Use Multi-Byte Character Set"
           is already selected .We can change by clicking the drop down button at left side.
        c) From there we can choose any option among all possible values .
        d)Then Click Ok or Apply to set.

(4)What is the code unit for each set?
Ans:-Here is the code unit for each character set:-
1)US-ASCII       -  7bits
2)UTF-8             - 8bits
3)EBCDIC         - 8bits
4)UTF-16           -16 bits
5)UTF-32           -32 bits



Compatibility of various data types and modifiers

Here we have three figures which explain us about compatibility of various modifiers.We should careful about following things:-



1)Signed and unsigned modifiers are only used with char and int.
2)Short used with only int.
3)Long used with int,float,double.
4)By default ints & chars are signed.
5)long long is only compatible with int





Unusual behaviour of signed and unsigned modifier

Signed and unsigned modifiers are not compatible with float and double.But if we use them with double and float there is only display an intellisense error and when we compile the program ,it shows nothing as an error.So we should be attentive while using signed and unsigned because compiler shows nothing as an error and compiler takes something as a default.Here is a program to describe the behaviour of signed and unsigned :-



 Here we can see that when signed and unsigned float printed as a float it gives zero.Similarly in the case of signed and unsigned double it also returns zero.Here we can seen one more thing that the value of integer a when printed as a float then it also returns zero.It means we must never use an integer as float.

Monday, 4 March 2013

Qualifiers in C

Today ,I run a program for qualifiers in C.There are basically three qualifiers in C which are used in different styles according to their use :-

1)volatile:-The volatile qualifier maintain consistency of memory access to data objects.The volatile keyword is intended to prevent the compiler from applying any optimization on the code that assume values of variable cannot change "on their own".The volatile keyword is used to declare that an object can be modified in the program by something such as the operating system,the hardware or a concurrently executing thread..It can be used with four types:-

int * volatile ic=&v4;        //a volatile pointer to an integer ,the value of integer can be changed.
volatile int *ci=&v5;        // a pointer to a volatile integer the value of integer cannot be changed .
int volatile *icptr=&v6;       //same as second
volatile int* volatilet cicptr=&v7;       //It is a volatile pointer to a vloatile integer so either  the integer can be changed or the pointer to point anything else.

                                                             The volatile object each time read from memory each time their values is needed and written back to memory each time they changed.The volatile qualifier declares a data object that can its value change in ways outside  the control or detection of the compiler .The compiler is thereby notified not to apply certain optimization to code referring to the project.We can understand it with this example:-

int xyz=100;
while(xyz==100)
{
//code
}

 This program gets compiled ,the compiler may optimize this code.If it finds that the program never ever makes any attempt to change the value of xyz.So it may optimize the code by changing it from "while(xyz==100)"  to "while(true)" because it is slow to compare each time the value of xyz to 100.
                                            But this is not desirable in each case to optimize the code because it is possible in the above case the value of xyz may be changed by an another cause outside the program.which is compiler is not aware of.So In this case we declare the integer xyz as a volatile and it stops the compiler to optimize the code.

volatile int xyz=100;

In C /C++ volatile keyword is intended to:
1)allow access to memory mapped devices
2)allow uses of variables between setjmp and longjmp
3)allow uses of  sig_atomic_t variables in signal handlers

We can use the following program to understand the volatile keyword:-


#include <iostream>
#include <windows.h>
using namespace std;

volatile bool Sentinel = true;
int CriticalData = 0;

unsigned ThreadFunc1( void* pArguments ) {
   while (Sentinel)
      Sleep(0);   // volatile spin lock

   // CriticalData load guaranteed after every load of Sentinel
   cout << "Critical Data = " << CriticalData << endl;
   return 0;
} 

unsigned  ThreadFunc2( void* pArguments ) {
   Sleep(2000);
   CriticalData++;   // guaranteed to occur before write to Sentinel
   Sentinel = false; // exit critical section
   return 0;
}

int main() {
   HANDLE hThread1, hThread2; 
   DWORD retCode;

   hThread1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadFunc1,
      NULL, 0, NULL);
   hThread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadFunc2,
      NULL, 0, NULL);

   if (hThread1 == NULL || hThread2 == NULL)       {
      cout << "CreateThread failed." << endl; 
      return 1;
   }

   retCode = WaitForSingleObject(hThread1,3000);

   CloseHandle(hThread1);
   CloseHandle(hThread2);

   if (retCode == WAIT_OBJECT_0 && CriticalData == 1 )
      cout << "Success" << endl;
   else
      cout << "Failure" << endl;
}

In this we can see that there is two thread handler declare which called two thread functions which are executed parrallely.In the first function we can see that the Sentinel is true so the function is in an infinite loop .When the second function starts its execution parrallaly the value of critical data incremented to one and the the value of Sentinel become false  and the value of critical data is printed one. 


2)Const:-The const qulaifier explicitly declares an data object that cannot be changed .Its value is set at initialization.We cannot use a const variable in expression requiring a modifiable lvalue.It can be used with four types:-
int * const ic=&v4;        //a const pointer to an integer ,the value of integer can be changed.The value of pointer cannot be changed
const int *ci=&v5;        // a pointer to a const integer the value of integer cannot be changed .The value of pointer can  be changed   .

int const *icptr=&v6;       //same as second
const int* const cicptr=&v7;       //It is a const pointer to a const integer so neither  the integer can be changed nor the point to anything else.
These 4 variation we can easily understand with these figures:-




We can easily understand it with the help of program snapshot:-

 





























*Commented lines are shows that these  const variables are not modifiable which we explained above.

3)restrict:-Basically there are two keywords _restrict and restrict_declspec.The _restrict keyword is valid only on variables .When restrict is used ,the compiler will not propagate the no-alias property of a variable.That is ,if you assigned a _restrict variable to a non-restrict variable ,the compiler will not imply that the non-_restrict variable is not aliased.The _restrict keyword similar to the restrict_declspec but _restrict can be used in C or C++ program.The restrict_declspec  is not a keyword in standard C/C++.It is a keyword C99 compiler .So if we use C99 compiler then it works fine.The restrict qualifier is only applied to a pointer .We know that a pointer is the address of a location in the memory.More than one pointer can access the same chunk of memory and modify it during the course of a program.But If we use restrict type of qualifier,it indicates to compiler if the memory addressed by the restrict-qualified pointer is modified ,then no other pointer will access the same memory .We can declare a restrict pointer by following syntax:-


 int * __restrict  f;

Here is snapshot for behaviour of a restricted variable.




Sunday, 3 March 2013

Behaviour of some Math.h functions

Today,I use some basic type of math.h functions and try to understand their behaviour.Here are some math.h functions which we use for study:-
1)abs
2)fabs
3)ceil
4)floor

1) abs :-This function returns absolute value of parameter.If a parameter having a value of -4 then it returns its value 4.It always takes and return int value.
2)fabs:-This is also having behaviour like abs But It always takes a double & returns double.F stands here
for floating-point argument.
3)ceil:-It calculates the ceiling value of parameter.It mean if a parameter having a value 4.1 then it returns 5 and value of a parameter is -4.1 then it returns 4.
4)floor:-It calculates the floor value of parameter .It mean if a parameter having a value 4.1 then it returns 4 and value of a parameter is -4.1 then it returns 5.

here is the snapshot of this program:-





Rounding a deimal number in C:-We can round the decimal number in C with following two methods:-

1)   FLOATVALUE = FLOOR(FLOATVALUE+0.5);
2)  FLOATVALUE = INT (FLOATVALUE+ 0.5);

Sunday, 24 February 2013

Right Shift of signed,unsigned char & int


Today ,I wrote a program for right shift of signed & unsigned int & char .Here we get some strange things.We need to understand it through program,Here is the snapshot of the program:-


Here we can see that signed char sc is different printed compare to inserted value.This is an anomaly.This is done because the the MSB is 1 But in case of signed char sc1 the printd value is same as inserted .This is because of value of MSB which is zero.In these if we take right shift of both we seen that In the case of  sc the value is unchanged because if we right shift the signed char or int it right shift the all bits & MSB equal to the MSB of original value either it is zero or one.In the case of unsigned char & int it right shift all the bits & MSB becomes Zero.These changes we can easily seen in the program.In the case of si & sc there is no change in right shift because MSB is one.