Constants, Variables and Data Types in C

In this post we will explain the basic things of C like constants, variables, and data types.

If you have not read Overview of C and want to read that first you may click here

  • Introduction

    •  A programming language helps to process certain kind of data consisting of numbers, characters and strings and to provide useful output.
    • The task of processing a data is accomplished by executing a sequence of precise instruction called a program.
    • These instruction or program is constructed or written or formed using symbols and words according to some strict rules which is called syntax rules.
    •  Each instruction should follow the syntax instruction of respective information.
    •  Like other Languages C also has its own syntax library or Grammar.

  • Character Set

    • The Character set are used to form words, numbers, and expressions depend upon the computer on which the program is run.
    • The character in C are grouped in to following categories.
      1. Letters
      2. Digits
      3. Special characters
      4. white spaces
    • Here in this below image all those character set are listed.
      C Character Set












  • C tokens

    • In a passage of text, individual words and punctuation marks are called token. Similarly, in a C program the smallest individual units are known as C tokens.
    • C has six types of tokens as shown in figure above.

  • Key Words and identifiers.

    • Every C word is classified as either a keyword or an identifier. All keywords have fixed meaning and these meanings cannot be changed.
    • Keywords serve as basic building blocks for the program statements.
    • The list of all the keyword of C are listed in below table.

    • Auto
      Double
      Int
      Struct
      Break
      else
      Long
      Switch
      Case
      Enum
      Register
      typedef
      Char
      Extern
      Return
      Union
      Const
      Float
      Short
      Unsigned
      Continue
      For
      Signed
      Void
      Default
      Goto
      Sizeof
      Volatile
      do
      If
      Static
      While
    • Identifiers refers to the name of variables, function and arrays. these are user-defined names and consist of a a sequence of letters and digits with a letter as a first character.

  • Constants
    • Constants in C refers to fixed values that does not change.
      C Constant

















    • Integer Constants
      • An integer constant refers to a sequence of digits.
      • there are three types of integer basically,

        • decimal integer (sets of digits,0 to 9,preceded by + or - optionally.
          • For e.g. 9999   436    -1000  +1247
        • octal integer(sets of digits from 0 to 7, with a leading 0
          • for e.g   045     0257    0361
        • hexadecimal integer(sequence of digits preceded by 0x, also include alphabets from A to F OR a to f, representing numbers from 10 to 15)
          • for e.g.  0X2    0X9F     0XEFA
        • Octal and hexadecimal are rarely used in programming.
        • The largest integer values that can be stored is machine dependent.
        • It 32767 for 16 bit and 2,147,483,647 on 32 bit machines

    • Real Constants
        • Integer numbers are inadequate to represent quantities that are vary continuously, such as distances, heights, temperatures, prices, and so on.
        • These quantities are represented by numbers having fractional parts like 35.543. Such numbers are called floating points or Real constants.
        • A real number may also be expressed in exponential notation. 
          • for e.g. 315.78 may be written as 3.1578e2 in exponential notation. e means multiply by 10^2.

    • Single character constants
        • A single character constant contains a single character enclosed within a pair of single quote marks.
          • Example '5', 'X', ';',  ','  
        • Note that the character constant 5 is not as same as number 5.
        • Character constant have integer values known as ASCII values.
          • for e.g. printf("%d",'a'); would print 97 as output
          • Similarly printf("%c",'97'); would print 'a' as output(without inverted commas)
        • Since each character constant represent a integer value, it is also possible to perform arithmetic operations on character constants.

    • String Constants
        • A string constant is a sequence of characters enclosed in doubles quotes. The  character may be letters numbers, special characters and blank spaces. 
          • Examples are "Hello!"  "I AM FINE"   "1996"    "abc +98-Iqu"  "X"
        • Here, in above example, X is not equivalent to character constant X. Also it does not consist of its integer value.
        • Character strings are used in programs frequently to make it more meaningful.

    • Backslash Character constants
      • C supports some special backslash character constant that are useful in output functions.
      • Below given is the list of such constants and their functions/meanings
        Constants
        Meanings
        ‘\a’
        Audible alert(bell)
        ‘\b’
        Back space
        ‘\f’
        Form feed
        ‘\n’
        New line
        ‘\r’
        Carriage return
        ‘\t’
        Horizontal tab
        ‘\v’
        Vertical tab
        ‘\”
        Single quote
        ‘\”’
        Double quote
        ‘\?’
        Question mark
        ‘\\’
        Backslash
        ‘10’
        null

    • Variables
      • A variable is a data name that is used to store data values.
      • They are not like constant, so the value stored in them can be changed during the execution of the program.
      • We have used few variables in example shown in Overview of C
      • The variable name can be chosen in a meaningful way so as to reflect its application or usage in the program, but it depends on the programmer that he/she remembers the application/usage or not.
      • There are some rules which should be followed to choose a  variable name
        • The can consist of letters with digits,and the underscore(at least one letter compulsory).
        • Some system also permits underscore first and then letter.
        • ANSI standard recognizes a length of 31 character. However, it is recommended to have a length of variable name not more than 8 characters, since many compiler treat only those first 8 character significant.
        • Variable names are case sensitive('Amount' is not the same as 'amount' or 'AMOUNT')
        • It should not be a keyword.
        • White space is not allowed(use underscore instead)

    • Data Types
      • C language is rich in its data types.
      • The variety of data types available allow the programmer to select the type appropriate to the need of the application as well as the machine.
      • C supports three classes of data types
        1. Primary(fundamental/basic data types){int, float, char etc.)
        2. Derived data types {arrays,structures,unions}
        3. User-defined data types {}

        • All C compilers support five fundamental data types, namely,
          • Integer(int)
          • Floating point(float)
          • Character(char)
          • Double precision floating point(double)
          • void.
        • Many of them also offer extended data types such as long int and long double.
        • Various data type and the terminology used to describe them are shown below
          Primary Data Types

      • Integer Type
        • Integer are whole numbers with a range of values supported by a particular machine.
        • Integer numbers are defined in C by the keyword int.
        • If we use a 16 bit word length, then the size of int that can be stored is limited to -32768 to 32767.
        • Similarly a 32 bit word length can store an integer ranging from -2,147,483,648 to 2,147,483,647.
        • In order to provide some control over the storage space, C has three classes of integer, namely short int, int, and long int in both signed and unsigned forms.
        • Unlike signed integers, unsigned integers use all the bits for the magnitude of the numbers and are always positive. Therefore, for a 16 bit machine, the range of unsigned integer number will be from 0 to 65,535.

      • Floating point types
        • Floating point(real numbers) are stored in 32 bits(on all 16 bit and 32 bit), with 6 digits of precision.
        • Floating point numbers are defined in C by the keyword float.
        • When more accuracy is required the type double is used instead of float.
        • A double data type uses 64 bits and gives precision of 14 digits.
        • To extend precision further long double is used which uses 80 bits.

      • Void types
        • The void types has no values .this is usually to specify the type of functions. The type of a function is said to be void when is does not return any value to the calling function. It can also play the role of a generic type, meaning that it can represent any of the other standard types

      • Character type
        • A single character can be defined as char type data.
        • They are usually stored in 8 bits of internal storage.
        • The qualifier signed or unsigned may be used to explicitly applied to char.
        • While unsigned chars have values between 0 to 255, signed chars have values from -128 to 127.
          Type
          Size(bits)
          Range
          Char or signed char
          8
          -128 to 127
          Unsigned char
          8
          0 to 255
          Int or signed int
          16
          -32,768 to 32,767
          Unsigned int
          16
          0 to 65,536
          Short int or signed short int
          8
          -128 to 127
          Unsigned short int
          8
          0 to 255
          Long int or signed long int
          32
          -2,147,483,648 to 2,147,483,647
          Unsigned long int
          32
          0 to 4,294,967,295
          Float
          32
          3.4E-38 to 3.4E+38
          Double
          64
          1.7E-308 to 1.7+308
          Long double
          80
          3.4E-4932to1.1E+4932


      • Declaration of variables
        • Declaration does two things
          • It tells the compiler what the variable name is.
          • It specifies what type of data the variable will hold.
        • Declaration of variable must be done before they are used in the program.

      • Primary declaration

      • A variable can be used to store value of any data type, i.e the name of variable has nothing to do with the data type, its just for understanding of what the variable is used for.
      • The general syntax of declaring a variable is: -

      data-type v1,v1,v3.....;

      • v1, v2, v3 are variable names which are separated by commas, and that statement ends with a semi colon.
      • for e.g: -

      int count;
      int number, total;
      double ratio;
        • In above example ,int and double are the keywords to represent data types.
        • One example program is shown in our Over view of C post which you can check here
        • If a variable is used without declaration it will give error UNDEFINED SYMBOL, where it is used.

      • User defined data type declaration
        • C supports a feature known as ' type definition' that allows users to define an identifier that would represent an existing data type. The user defined data type identifier can later be used to declare variables.
      typedef int units;
      typedef float marks;
        • Here units and marks are declared as user defined data types int and float and using them a programmer can declare any variables of that data type instead of using int and float keyword.
      units amount;
      marks class_3;

      • Declaration of storage class
        • variable in C can have not only data type but also class that provides information about their location and visibility. The storage class decides the program within which the variables are recognized.
        • let us take an example: -
                           /*Example of storage class*/
                           int a;
                           main()
                                      {
                                        int b;
                                        float amount;
                                        /*Program section*/
                                        ..
                                        .....
                                        function();
                                        }
                     int funciton()
                                        {
                                          int b;
                                          float sum;
                                          }
        • The variable 'a' which has been declared before main() function is called Global Variable.
        • It can be used anywhere in the entire program.
        • They are also known as External Variables.
        • The Other variables 'b, amount and sum' are local variable of respective functions in which they are called.
        • They cannot be used directly out of that function.
        • But their values can be accessed out of that functions through pointers(pointers will be discussed in future post)
        • Note that variable 'b' has been used in two different function one main() and other user defined function. The change in value of any of them will not affect the value stored in other variable 'b'.
        • C provides a variety of storage class specifiers that can be used to declare explicitly the scope and lifetime of a variable.
        • Scope and lifetime are important only in multi-function programs.(It will be discussed later on)
        • For now just remember that there are four storage class specifiers.
          • Auto
          • register
          • static
          • extern
        • These storage class are another qualifiers (like long or unsigned) that can be added to a variable declaration as shown below;
      auto int count;
      register char ch;
      static int x;
      extern long total;

      • Assigning Values to variables
        • Variables are used for use in program statements such as,
                      main()
                                {
                                  int a =3,b=5,sum;
                                   sum= a+b;
                                   printf("%d     %d     %d", a,b,sum);
                                   }

      • Assignment Statement

        • The values are assigned to any variable using assignment operator '='.
        • Here in this program the values are assigned to variable 'a' and 'b' during declaration which is one of the basic method of declaration of values to a variable.
        • We have already used some example before and the above example is also one of the example to use assignment operator.
        • As you can see in the above example, C also allows multiple assignment in one line only.
        • The assignment statement only mean that the value of variable on the left side is equal to the value of the variable on the right side.
        • Hence the statement, 'A=A+3;' will result in the value of A increased by 3, since it is assigned that the new value of A =Old Value of A + 3;

        • C also allows to assign initial value to multiple variables in a single line which is called initialization.
        • a=b=c=0;
        • p=q=r=MAX;      /* MAX is a constant variable defined at the beginning*/
        • External and static variables are default to be zero, while automatic variable need to be initialized else they will contain garbage values.

      • Reading Values from Keyboard

      • Another way of giving values to variable is to get values from users or standard input of the system, i.e Keyboard.
      • 'scanf ' is a function used to get input from the standard input of the system. It is a function of STDIO.h(standard input output) header file like 'printf '.
      • The syntax for using this function is:
        • scanf("control string", &variable1,&variable2,....);
      • The control string contains the formats of data being stored. The ampersand symbol '& ' before each variable name is an operator that specifies the address of variable.
      • Let us look at some example:
        • scanf("%d",&m)
        • Here 'm ' is an integer variable hence %d is used to receive an integer value similar to printf function.
      • In similar manner multiple values can also be received in one scanf function:
        • scanf("%d %f",&a,&b);
        • Here a space in between the two receiving data must be inserted so that multiple values can be stored in multiple variables simultaneously.
      • Once the value is inserted than return Key should be pressed to get out of this function and let the program move on to the forthcoming statements.



    • Example: -
                          /*This is a program to explain Scanf function*/
                          main()
                                    {
                                       int a,b,sum;
                                       scanf("%d",&a);
                                       scanf("%d",&b);
                                       printf("A= %d   B=%b",a,b);
                                       sum=a+b;
                                       printf("Sum= %d",sum);
                                       }

        • Here in above example we have used assignment operator as well as scanf function.
        • In the last printf function the sum could also be achieved directly without using an extra variable 'sum' by using this printf statement.
          • printf("sum= %d",a+b);
        • And it is advisable to use variables as per use only so that your program will use lesss memory space and less time consuming too.

    • Defining Symbolic constant
        • We often use some constant values in a program which are either universal constant or needed to be used as constant values for the entire program.
        • example 'pi' = 3.14159 or acceleration of gravity 'g' = 9.8 m/s^2
        • For such demand of constants if we just use variables then we may face two problems
          • problem in modification
          • problem in understanding the program

    • Modifiability
      • We may like to change the value of 'pi' from 3.142 to 3.14159 to get more accurate results in the program, hence for the modification we have to search throughout the program and explicitly change the values of the constant wherever it has been used.
      • If any of those values is left as it is than it may produce bad/unwanted or wrong outputs which will require further search in the coding.

    • Understandability
      • When a numeric value appears in a program, its use is not always clear, especially when the same value means different things in different places. 
      • For example, the number 100 may also represent a no. of students in a class and also total no. of marks in a subject.
      • Hence, there is always a possibility being a human that we may forget which value is for which purpose, after some days.
      • Assignment of such constants to a symbolic name frees us from these problems. For example, we may use the name STRENGTH to define the no. of students and TOTAL to define the total no. of marks in a subject.
      • These constant values are defined at the beginning of the program by using #define function.(you can see what #include mean - here)
      • Example
        • #define PI 3.14;
        • #define MAX 100;
      • There are some rules for the #define statement.
        • The symbolic constant, like PI and MAX in above example, do not appear in declaration section separately.
        • They have same form as variable names.
        • There should not be space between # and define.
        • There should be a blank space between #define and the symbolic name and the Symbolic name and the constant value and no semi colon is needed at the end.
        • Symbolic names are not defined for data types, the data type are depended on type of constants.
        • #define statement may appear anywhere in the program but before it is referenced in the program.

    • Declaring a Variable as Constant:
        • If a program needs a variable's value to be constant than we can use const qualifier before the data type of that variable during declaration of that variable.
          • syntax:- const data type variable=constant value;
          • e.g const int max= 40;

    • Declaring a Variable as Volatile:

        • ANSI standard defines another qualifier volatile that could be used to tell explicitly the computer that a variable's value may be changed at any time by some external sources(outside the program). For example:
      volatile int date;

        • The value of date may be altered by some external factors even if it does not appear on the left-hand side of an assignment statement. When we declare a variable a variable as volatile, the compiler will examine the value of the variable each time it is encountered to see any external alteration altered the program or not.
        • If we don't want that value of volatile variable not to be altered within the program but by external source only than we can use const with volatile.
        • volatile const int location =100;

      • Overflow and Underflow of data:
        • Problem of data overflow occurs when the value of a variable is wither too big or too small for the data type to hold. The largest value that a variable can hold also depends on the machine.
        • Since the floating point values are rounded off to the number of significant digits allowed(or specified), an overflow normally results in the largest possible real value, whereas an underflow results in zero.
        • Integers are always exact within the limits of the range of the integral data types used. However, an overflow which is a serious problem may occur if the data type does not match the value of the constant. 
        • C does not provide any warning or indication of the integer overflow.
        • It simply gives incorrect results.(overflow normally produces negative values)
        • We should therefore exercise greater care to define correct data types for handling the input/output values.

      Comments

      1. Good blog about data integration. If you want to know more about how to integrate data, please contact us from the links below

        The data warehouse interview questions are providing to be quite helpful and here with the help of expert written pages and links you can learn more facts about it at ease. The informatica interview questions and answers for experienced has earned the value and many students or individual looking for his profession is seen following this particular book or questionnaire for reference purpose.

        ReplyDelete

      Post a Comment

      Popular posts from this blog

      Windows phone Wifi connectivity problem.

      Create Excel file using Java: Apache POI - PART - 2: Line Chart