Unit 2
Constants, Variables & Data Types in ‘C’
- What is Character set?
As every language contains a set of characters used to construct words, statements, etc., C language also has a set of characters which include alphabets, digits, and special symbols. C language supports a total of 256 characters.
Every C program contains statements. These statements are constructed using words and these words are constructed using characters from C character set. C language character set contains the following set of characters...
- Alphabets
- Digits
- Special Symbols
Alphabets
C language supports all the alphabets from the English language. Lower and upper case letters together support 52 alphabets.
Lower case letters - a to z
UPPER CASE LETTERS - A to Z
Digits
C language supports 10 digits which are used to construct numerical values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
C language supports a rich set of special symbols that include symbols to perform mathematical operations, to check conditions, white spaces, backspaces, and other special symbols.
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL bell backspace verticaltab etc.,
Every character in C language has its equivalent ASCII (American Standard Code for Information Interchange) value.
2. What are C tokens?
Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following C statement consists of five tokens −
Printf("Hello, World! \n");
The individual tokens are −
Printf
(
"Hello, World! \n"
)
;
Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.
Given below are two different statements −
Printf("Hello, World! \n");
Return 0;
Comments
Comments are like helping text in your C program and they are ignored by the compiler. They start with /* and terminate with the characters */ as shown below −
/* my first program in C */
You cannot have comments within comments and they do not occur within a string or character literals.
3. Explain Identifiers and keywords
A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z, a to z, or an underscore ‘_’ followed by zero or more letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-sensitive programming language. Here are some examples of acceptable identifiers −
Mohd zara abc move_name a_123
Myname50 _temp j a23b9 retVal
Keywords
The following list shows the reserved words in C. These reserved words may not be used as constants or variables or any other identifier names.
Auto | Else | Long | Switch |
Break | Enum | Register | Typedef |
Case | Extern | Return | Union |
Char | Float | Short | Unsigned |
Const | For | Signed | Void |
Continue | Goto | Sizeof | Volatile |
Default | If | Static | While |
Do | Int | Struct | _Packed |
Double |
|
|
|
4. What is Whitespace in C?
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement −
Int age;
There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement −
Fruit = apples + oranges; // get the total fruit
Variables are the names you give to computer memory locations which are used to store values in a computer program.
Here are the following three simple steps −
- Create variables with appropriate names.
- Store your values in those two variables.
- Retrieve and use the stored values from the variables.
When creating a variable, we need to declare the data type it contains.
Programming languages define data types differently.
For example, almost all languages differentiate between ‘integers’ (or whole numbers, eg 12), ‘non-integers’ (numbers with decimals, eg 0.24), and ‘characters’ (letters of the alphabet or words).
- Char – a single 16-bit Unicode character, such as a letter, decimal or punctuation symbol.
- Boolean – can have only two possible values: true (1) or false (0). This data type is useful in conditional statements.
- Byte - has a minimum value of -128 and a maximum value of 127 (inclusive).
- Short– has a minimum value of -32,768 and a maximum value of 32,767
- Int: – has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
- Long – has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).
- Float – a floating point number with 32-bits of precision
- Double – this is a double precision floating point number.
5. Explain Data types in detail
Data Declarations
Declarations serve two purposes:
They tell the compiler to set aside an appropriate amount of space in memory for the program’s data (variables).
They enable the compiler to correctly operate on the variables. The compiler needs to know the data type to correctly operate on a variable. The compiler needs to know how many bytes are used by variables and the format of the bits. The meaning of the binary bits of a variable are different for different data types.
- Char is 8 bit (1 byte) ASCII, but can also store numeric data.
- Int is 4 byte 2’s complement.
- Short is 2 byte 2’s complement.
- Long is 8 byte 2’s complement.
- Unsigned (int, short, and long) are straight binary
- Float is 4 byte IEEE Floating Point Single Precision Standard.
- Double is 8 byte IEEE Floating Point Double Precision Standard.
Character - integer relation
The ASCII code is a set of integer numbers used to represent characters.
Char c = 'a'; /* 'a' has ASCII value 97 */
Int i = 65; /* 65 is ASCII for 'A' */
Printf( "%c", c + 1 ); /* b */
Printf( "%d", c + 2 ); /* 99 */
Printf( "%c", i + 3 ); /* D */
Integers
A variations of int (unsigned, long, ...) are stored binary data which is directly translated to it’s base-10 value.
Floating point data
Variables of type float and double are stored in three parts: the sign, the mantissa (normalized value), and an exponent.
Sizeof
Because some variables take different amount of memory of different systems, C provides an operator which returns the number of bytes needed to store a given type of data.
i = sizeof(char);
j = sizeof(long);
k = sizeof(double);
The sizeof operator is very useful when manually allocating memory and dealing with complex data structures.
Conversions and Casts
Two mechanisms exist to convert data from one data type to another, implicit conversion and explicit conversion, which is also called casting.
Implicit conversion
If an arithmetic operation on two variables of differing types is performed, one of the variables is converted or promoted to the same data as the other before the operation is performed. In general, smaller data types are always promoted to the larger data type.
Explicit conversion or casts
The programmer can tell the compiler what types of conversions should be performed by using a cast. A cast is formed by putting a data type keyword in parenthesis in front of a variable name or expression.
x = (float)(m * j);
i = (int)x + k;
6. What are Constants and Variables?
Constant are same as variables but once initialized, cannot change by program.
Constants are fixed values and also called as literals.
Example –
- Integer constants – 2,7,0,454,1204.
- Real constants – 6.7, 4556.78,3432.988
- Character constants – ‘a’,’G’.
- String Constants – “Hello World”.
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
7. Explain Variables in detail
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types −
Sr.No. | Type & Description |
1 | Char Typically a single octet(one byte). It is an integer type. |
2 | Int The most natural size of integer for the machine. |
3 | Float A single-precision floating point value. |
4 | Double A double-precision floating point value. |
5 | Void Represents the absence of type. |
C programming language also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study only basic variable types.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows −
Type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined object; and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −
Int i, j, k;
Char c, ch;
Float f, salary;
Double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows −
Type variable_name = value;
Some examples are −
Extern int d = 3, f = 5; // declaration of d and f.
Int d = 3, f = 5; // definition and initializing d and f.
Byte z = 22; // definition and initializes z.
Char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables are undefined.
8. Explain Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable. A variable definition has its meaning at the time of compilation only, the compiler needs actual variable definition at the time of linking the program.
A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.
Example
Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function −
#include <stdio.h>
// Variable declaration:
Extern int a, b;
Extern int c;
Extern float f;
Int main () {
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of c : 30
Value of f : 23.333334
The same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example −
// function declaration
Int func();
Int main() {
// function call
int i = func();
}
// function definition
Int func() {
return 0;
}
9. Explain Assigning Values to Variables
A variable assignment is a process of assigning a value to a variable.
Int width = 60;
Int age = 31;
Some rules
- A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and the underscore character.
- The first character must be a letter or underscore.
- Blank spaces cannot be used in variable names.
- Special characters like #, $ are not allowed.
- C keywords cannot be used as variable names.
- Variable names are case sensitive.
- Values of the variables can be numeric or alphabetic.
- Variable type can be char, int, float, double, or void.
Example
#include<stdio.h>
Void main()
{
/* c program to print value of a variable */ int age = 33;
printf("I am %d years old.\n", age);
}
Output
I am 33 years old.
10. What is declaring a variable as Constant?
Variables can be declared as constant using the const keyword or the #define preprocessor directive. Details about these are given as follows.
The const keyword
Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.
A program that demonstrates the declaration of constant variables in C using const keyword is given as follows.
Example
#include <stdio.h>
Int main() {
Const int a;
Const int b = 12;
Printf("The default value of variable a : %d", a);
Printf("\nThe value of variable b : %d", b);
Return 0;
}
The output of the above program is as follows.
The default value of variable a : 0
The value of variable b : 12
The #define preprocessor directive
Variables can be declared as constants by using the #define preprocessor directive as it declares an alias for any value.
A program that demonstrates the declaration of constant variables in C using #define preprocessor directive is given as follows.
Example
#include <stdio.h>
#define num 25
Int main() {
Printf("The value of num is: %d", num);
Return 0;
}
Output
The output of the above program is as follows.
The value of num is: 25