Unit 2
Constants, Variables & Data Types in ‘C’
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 vertical tab etc.,
Every character in C language has its equivalent ASCII (American Standard Code for Information Interchange) value.
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.
Identifiers
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 |
|
|
|
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.
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;
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.
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.
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;
}
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.
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
The value of Pi is a constant, it never changes. The only question we really have with Pi is, “How precise do we want to be?” We need to insure a uniform amount of precision throughout the program, so that the value will not be changed by mistake. This means that we do not want the value of Pi to vary from function to function.
After all, the whole point of variables is that they are mutable. If we store Pi in a variable, there is nothing to insure that the value won’t be modified by accident.
A symbolic constant is a constant that is represented by a symbol in our program. Whenever we need the symbolic constant’s value in our program, we can its name just as we would use a variable’s name.
There are two ways to implement symbolic constants in C. Our first option here is to define Pi as a symbol that will be replaced in the program by a specified value during compilation. In this case, Pi wouldn’t be a variable at all, it would more like an alias or stand-in for the value it represents. We do this using what is know as a #define directive.
#include <stdio.h>
#define PI 3.14159
int main(void){
double diameter = 5.5;
double radius = diameter / 2.0;
double circumference = 2.0*radius*PI;
double area = PI*radius*radius;
printf("The diameter of the circle is %.2f\n", diameter);
printf("The radius of the circle is %.2f\n", radius);
printf("The circumference of the circle is %.3f\n", circumference);
printf("The area of the circle is %.3f\n", area);
return 0;
}
Note that by convention identifiers that appear in a #define statement are written in capital letters.
All #define directives should be grouped together near the beginning of the file and before the main() function.
#include <stdio.h>
#define GRAMS_PER_POUND 454
#define METERS_PER_FOOT .3048
int main(void){
int pounds1 = 115;
int pounds2 = 175;
int feet1 = 6;
int feet2 = 300;
printf("%d pounds = %d grams\n", pounds1, pounds1 * GRAMS_PER_POUND);
printf("%d pounds = %d grams\n", pounds2, pounds2 * GRAMS_PER_POUND);
printf("%d feet = %f meters\n", feet1, METERS_PER_FOOT * (double)feet1);
printf("%d feet = %f meters\n", feet2, METERS_PER_FOOT * (double)feet2);
return 0;
}
The second way to define a symbolic constant is with the const keyword. We can make the value of any variable immutable by prefixing the type name with the keyword const when we declare the variable. A value is initialized at the time of declaration and is then prohibited from being changed. Any code that attempts to change its value will be flagged as an error and the compilation will fail.
#include <stdio.h>
int main(void){
const double Pi = 3.14159;
double radius = 11.11;
double circumference = radius * 2.0 * Pi;
double area = radius * radius * Pi;
printf("The radius of the circle is %f\n", radius);
printf("The circumference of the circle is %f\n", circumference);
printf("The area of the circle is %f\n", area);
return 0;
}
Note that many functions in the standard library use const in their parameter declarations.
The header file <limits.h> defines symbolic constants that represent values for the limits of each integer data type.
#include <stdio.h>
#include <limits.h>
int main(void){
printf("The char type stores values from %d to %d\n", CHAR_MIN, CHAR_MAX);
printf("The int type stores values from %d to %d\n", INT_MIN, INT_MAX);
printf("The unsigned int type stores values from 0 to %u\n", UINT_MAX);
printf("The long long int type stores values form %lld to %lld\n", LLONG_MIN, LLONG_MAX);
return 0;
}