Programming With Integers - Initial Values of Variables

Chapter chap2 section 7

You may have wondered what values are stored in the variables x and y in the sum of two numbers programs before any values have been read in. The answer is that the values are indeterminate, this means that you cannot make any assumptions about what values are initially in any location. On many systems you will find that the initial value is zero but you must not rely on this.

The following program demonstrates what happens if you do not set initial values.

main()
{
	int	x;
	int	y;
	printf("Initial value of x is %d\n",x);
	printf("Initial value of y is %d\n",y);
}
On the IBM 6150 it produced the following output.
Initial value of x is 0
Initial value of y is 0
On the SUN Sparc Station the result was
Initial value of x is 0
Initial value of y is 32
And finally Turbo C gave the following results
Initial value of x is 0
Initial value of y is 248

Should you want a variable to have some defined initial value then this can be included within the declaration by following the variable name by an equals symbol (=) and a value in the declaration. This is known as initialisation. The following program shows the initialisation of variables.

main()
{
	int	x=3,y=4;
	printf("The sum of %d and %d is %d\n",x,y,x+y);
}
When compiled and run it produced the following output.
The sum of 3 and 4 is 7
The initialisation is part of the declaration. Initialised and uninitialiased variables can be mixed in the same declaration. For example

int x,y=7,z;

In fact a variable can be initialised to any expression whose value can be determined by the compiler. This means that initialisations such as

int	x=4+7;
int	z=3,y=z+6;

are acceptable although rather pointless and not conventional programming.


Output Layout Control