INITIALIZING DATA VARIABLES AT DECLARATION TIME
Unlike PASCAL, in C variables may be initialized with a value
when they are declared. Consider the following declaration, which
declares an integer variable count which is initialized to
10.
int count = 10;
SIMPLE ASSIGNMENT OF VALUES TO
VARIABLES
The = operator is used to assign values to data variables.
Consider the following statement, which assigns the value 32 an
integer variable count, and the letter A to the
character variable letter
count = 32; letter = 'A';
THE VALUE OF VARIABLES AT DECLARATION TIME
Lets examine what the default value a variable is assigned when
its declared. To do this, lets consider the following program,
which declares two variables, count which is an integer,
and letter which is a character.
Neither variable is pre-initialized. The value of each variable is printed out using a printf() statement.
#include <stdio.h> main() { int count; char letter; printf("Count = %d\n", count); printf("Letter = %c\n", letter); } Sample program output Count = 26494 Letter = f
It can be seen from the sample output that the values which each of the variables take on at declaration time are no-zero. In C, this is common, and programmers must ensure that variables are assigned values before using them.
If the program was run again, the output could well have different values for each of the variables. We can never assume that variables declare in the manner above will take on a specific value.
Some compilers may issue warnings related to the use of variables, and Turbo C from Borland issues the following warning,
possible use of 'count' before definition in function main
RADIX CHANGING
Data numbers may be expressed in any base by simply altering the
modifier, e.g., decimal, octal, or hexadecimal. This is achieved
by the letter which follows the % sign related to the printf
argument.
#include <stdio.h> main() /* Prints the same value in Decimal, Hex and Octal */ { int number = 100; printf("In decimal the number is %d\n", number); printf("In hex the number is %x\n", number); printf("In octal the number is %o\n", number); /* what about %X\n as an argument? */ } Sample program output In decimal the number is 100 In hex the number is 64 In octal the number is 144
Note how the variable number is initialized to zero at the time of its declaration.
DEFINING VARIABLES IN OCTAL AND HEXADECIMAL
Often, when writing systems programs, the programmer needs to use
a different number base rather than the default decimal.
Integer constants can be defined in octal or hex by using the associated prefix, e.g., to define an integer as an octal constant use 0 (zero)
int sum = 0567;
To define an integer as a hex constant use 0x (zero followed by x or X)
int sum = 0x7ab4; int flag = 0x7AB4; /* Note upper or lowercase hex ok */