A variable
is assigned (or initialized) by assignment operator =.
Syntax:
type var
= Constant;
Global and static local
variables are initialized
only at the start of program.
Local variables
(excluding static local variables) are initialized each time in the block in
which they are declared.
If a local variable is
not initialized or assigned to a value (constant), it will have unknown value.
global and static local
variables that are not initialized automatically set to zero or null value.
Constant :
Sometimes also called as literals.
Constant can be a value of any basic data type.
For example:
Integer constants – any integer number, e.g. 0, 1,
5, 17,30 etc.
Float constant- any fractional number, e.g.
12.235, 3.141529, 2.714, 3.14e-10 etc.
[Note: C also allows to use scientific notation
for floating-point constants.]
Character constant – any single character (excluding
Backslash Character) enclosed in
single quotes, e.g. ‘a’,’4’, ‘%’ etc.
[Note: To get a Backslash Character we use double Backslash in single quotes e.g. ‘\\’.
See escape sequences.]
For assigning a character variable to null
character, we use either ‘\0’ or simply 0.
e.g.
char x = ‘\0’;
or
char x = 0;
For assigning a character variable to backslash
character we use ‘\\’.
e.g.
char x = ‘\\’;
Compiler optimizes a
numeric constant into the smallest compatible data type that can hold it. For
example: If integer is of 16 bit, 34 is int by default, but 23453453 is a long
int, even though the value 34 could fit into a character type, the compiler
will not cross type boundaries (excluding in the case of floating point
constants where a float constant is assumed to be doubles).
We can use a suffix to
specify a constant precisely, see below list.
Data Type
|
Constants
|
int
|
2, -4, 345 etc.
|
long int
|
2L, -4L, 3456789L, 67l, -41l etc.
|
long long
|
323434LL, 5657567ll, -5656ll etc.
|
unsigned int
|
2U, 4U, 876U, 7u, 768u etc.
|
unsigned long long
|
18446744073709551615ULL, 546ull etc.
|
float
|
34.34456F, -3.14256f, 2.6e-10f etc.
|
double
|
3.0,234.50, -9.765544545 etc.
|
long double
|
112324.45L,34534534645.455l etc.
|
Hexadecimal and Octal integer Constants:
An octal constant begins
with a 0 and hexadecimal constant begins with 0x,
for example:
int octa = 0123;
|
/* 83 in decimal */
|
int hexa = 0x123;
|
/* 291 in decimal */
|
[Note: In GNU GCC
compiler, we can also use 0b or 0B for binary constants.]
String Constants:
string is a set of characters
enclosed in double quotes.
For example:
“this is a string”, “a”, “1234”, “3.1415926”,
“#$a12” etc.
[Note: C
does not have a basic datatype of string but we can define string constant. To
store the value of string constant into a string variable, we require a
character array or character pointer. See arrays and pointers.]
[Note: `a` and “a” both are
different here. `a` is a character constant while “a” is a string constant.]