Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help
next up previous contents
Next: Aggregates Up: ANSI C for Programmers Previous: Compilation Stages   Contents

Variables and Literals

Variable names can't begin with a digit. Nor can they contain operators (like `.' or `-'). They have to be declared before being used. The available scalar types are char, short, int, long, float, double and long double. chars and the various lengths of integers can be signed (the default) or unsigned.

Often you don't explicitly have to convert types. If you operate on variables of different types, type conversion takes place auomatically. E.g. if you add an int and a float then the int will be converted to a float and the result will be a float.

unsigned int i;
float f = 3.14;
i = f;
will automatically set i to 3, truncating the real value. To explicitly convert types use casting; E.g.
i = (unsigned int) f;
Most conversions preserve the numerical value but occasionally this is not possible and overflow or loss of precision results. C won't warn you if this happens.

The length of an integer isn't the same on all machines. `sizeof (int)' will return the number of bytes used by an integer.

The scope of a variable is the block (the function, or { } pair) it's declared in, or the remainder of the file it's declared in. Variables declared outside of a block and functions can be accessed from other files unless they're declared to be static.

Variables declared in functions can preserve their value between calls if they are defined as static, otherwise they're automatic, getting recreated for each call of the function.

Character values can be written in various ways :- E.g. on machines that use ASCII

'A'  '\101'  '\x41'
all represent 65; the first using the ASCII A character, the second using octal and the third hexadecimal. The newline character is '\n'.

Integer and real values can be variously expressed:-

15L long integer 15
015 octal integer 15
0xF7 Hex (base 16) number F7
15.3e3F , a float
15.3e3 , a double
15.3e3L , a long double


next up previous contents
Next: Aggregates Up: ANSI C for Programmers Previous: Compilation Stages   Contents
Tim Love 2010-04-27