I'll take my chances with C types & operators, Sir
variable · constant · limits.h · floats.h · ctype.h · sign extension · truncation · string literal · string constant · #define · enum · wraparound · cast · two's complement · ones' complement · hexadecimal · octal · binary · EBCDIC · ASCII · static typing · dynamic typing · type inference · machine dependence · null terminator · automatic variable · integer division · truncation · overflow · underflow · short circuit · propositional logic · type conversion · cast · prefix · postfix · bitwise operators · arithmetic operators · arithmetic shift · logical shift · mask · getbits · ASCII arithmetic · hexadecimal · place value · precedence · software metrics
This post is more of a cheat sheet for rules and quirks in C type, operators and expressions. The companion post is K&R Chapter 2: Do you fear operators?. No narrative here, just the rules.
Variable names
- Made of letters and digits; must start with a letter. The underscore counts as a letter.
- Don’t begin names with an underscore, since library routines often use such names.
- Upper and lower case are distinct. Convention: lower case for variables, upper case for symbolic constants.
- At least the first 31 characters of an internal name are significant.
- External names may have fewer significant characters, since the linker handles them.
- Keywords (
if,else,int,float, and the rest) are reserved.
Basic types
| Type | Notes |
|---|---|
char | a single byte, holds one character in the local character set |
int | an integer, typically the natural word size of the machine |
float | single-precision floating point |
double | double-precision floating point |
Qualifiers
short,long,signed,unsigned.shortandintare at least 16 bits;longis at least 32 bits.shortis no longer thanint;intis no longer thanlong.- Actual sizes are machine-dependent.
<limits.h>and<float.h>hold symbolic constants for them. signedandunsignedapply tocharor any integer type.unsignedvalues are non-negative and obey arithmetic modulo .- Whether plain
charis signed or unsigned is machine-dependent. For portability, specifysignedorunsignedif storing non-character data in achar. long doubleis extended-precision floating point; its precision is implementation-defined.- Most machines use two’s complement for signed integers.
Constants
- Integer constant:
1234. SuffixLorlforlong,Uoruforunsigned,ULforunsigned long. - Leading
0means octal; leading0xor0Xmeans hexadecimal.31,037and0x1fare the same value. - Floating-point constants are
doubleby default. SuffixforFforfloat,lorLforlong double. - A character constant like
'x'is an integer whose value is that character’s numeric value in the machine’s character set. - Escape sequences:
\n\t\b\r\f\v\a\\\?\'\"\0\ooo(octal)\xhh(hex). '\0'is the null character, value zero. Written as'\0'rather than0to emphasize its character nature.- A string constant is characters in double quotes. Its internal representation ends with
'\0', so storage is one more byte than the characters written. strlen("hello")is 5; the array holding it takes 6 bytes.- A constant expression involves only constants and may be evaluated at compile time.
constdeclares a value will not be changed:const double e = 2.71828;. On an array argument it promises the function won’t modify the array.- An enumeration is a list of constant integer values:
enum boolean { NO, YES };. The first name is 0 unless given a value; later values increase by one from the previous. - Names in different enumerations must be distinct. Values need not be distinct within the same enumeration.
- Enums beat
#definebecause values can be generated for you and debuggers may print them by name.
Declarations and initialization
- All variables must be declared before use.
- External and static variables are initialized to zero by default.
- Automatic variables without an explicit initializer have undefined (garbage) values.
- For automatic variables the initializer may be any expression. For external and static variables it must be a constant expression, evaluated once before the program starts.
Arithmetic operators
- Binary:
+-*/%. - Integer division truncates the fractional part.
%gives the remainder; it cannot be applied tofloatordouble.- For negative operands, the direction of truncation for
/and the sign of the result for%are machine-dependent, as is the action on overflow or underflow. +and-share a precedence, lower than*/%, which is lower than unary+and-.- Arithmetic operators associate left to right.
Relational and logical operators
- Relational:
>>=<<=, all the same precedence. - Equality:
==!=, lower precedence than relational. - Relational operators are lower precedence than arithmetic, so
i < lim - 1meansi < (lim - 1). - Logical:
&&||.&&is higher precedence than||; both are lower than relational and equality. - Expressions joined by
&&or||evaluate left to right and stop as soon as the result is known. This short-circuiting is guaranteed by the language. - A relational or logical expression has the numeric value 1 if true, 0 if false.
- Unary
!converts non-zero to 0 and 0 to 1.
Type conversions
- Operands of different types are converted to a common type by a small set of rules.
- The only automatic conversions are narrower to wider, which can’t lose information, such as
inttofloat. - Conversions that might lose information, such as
floattoint, may warn but are legal. charis a small integer and may be used freely in arithmetic.- Conversions happen across assignment: the right side is converted to the type of the left, which is the type of the result.
- When a
doubleis converted tofloat, whether the value is rounded or truncated is implementation dependent. - Longer integers convert to shorter ones, or to
char, by dropping excess high-order bits. - Explicit conversion uses a cast:
(type-name) expression. - A cast produces a converted value; the variable itself is unchanged.
Increment and decrement
++adds 1,--subtracts 1.- Both work as prefix (
++n) and postfix (n++) operators. ++nincrements before the value is used;n++increments after.- Where the value isn’t used, the two forms are equivalent.
- They apply only to variables.
(i+j)++is illegal.
Bitwise operators
Applicable only to integral operands.
| Operator | Meaning |
|---|---|
& | bitwise AND |
| | bitwise inclusive OR |
^ | bitwise exclusive OR |
<< | left shift |
>> | right shift |
~ | one’s complement (unary) |
&masks off bits:n = n & 0177keeps the low seven bits.|turns bits on:x = x | SET_ON.^sets a 1 in each position where the operands differ.x << 2shifts left two positions, filling with zeros, equivalent to multiplying by 4.- Right-shifting an unsigned value always fills vacated bits with zero.
- Right-shifting a signed value fills with sign bits (arithmetic shift) on some machines and zeros (logical shift) on others.
~flips every 1 to 0 and every 0 to 1.- Prefer
x & ~077overx & 0177700; the first is independent of word length. - Bitwise is not logical:
1 & 2is0, but1 && 2is1.
Idiom: extract a bit field
/* getbits: get n bits from position p */
unsigned getbits(unsigned x, int p, int n) {
return (x >> (p+1-n)) & ~(~0 << n);
}
p+1-nis the shift that drops the field’s lowest bit to position 0.~(~0 << n)builds a mask ofnones on the right.- The
&clears everything above the field. - General pattern: shift down to position 0, then mask.
Assignment operators
+=-=*=/=%=<<=>>=&=^=|=.expr1 op= expr2is equivalent toexpr1 = (expr1) op (expr2), exceptexpr1is computed only once.- The implied parentheses matter:
x *= y + 1meansx = x * (y + 1), notx = x * y + 1. - An assignment is an expression and has a value, which is why
while ((c = getchar()) != EOF)works.
Conditional expression
expr1 ? expr2 : expr3.expr1is evaluated first. If non-zero,expr2becomes the value; otherwiseexpr3.- Only one of
expr2andexpr3is evaluated. - If their types differ, the result type follows the conversion rules.
- It is an expression, not a statement, so it can appear anywhere a value is expected.
Precedence and associativity
Highest to lowest:
| Operators | Associativity |
|---|---|
() [] -> . | left to right |
! ~ ++ -- + - * & (type) sizeof | right to left |
* / % | left to right |
+ - | left to right |
<< >> | left to right |
< <= > >= | left to right |
== != | left to right |
& | left to right |
^ | left to right |
| | left to right |
&& | left to right |
|| | left to right |
?: | right to left |
= += -= and the rest | right to left |
, | left to right |
Order of evaluation
What the language does not promise:
- The order in which an operator’s operands are evaluated is unspecified, except for
&&,||,?:and,. - In
x = f() + g();, either function may be evaluated first. - The order in which function arguments are evaluated is unspecified.
- Side effects within a single statement, such as
a[i] = i++;, can occur in any order. - Rule of thumb: don’t write code whose result depends on evaluation order.
Machine-dependent behaviour, quick list
Everything in this chapter that can differ between machines or compilers:
- Sizes of
int,short,long,float,double,long double. - Whether plain
charis signed or unsigned. - Truncation direction of
/and sign of%for negative operands. - Action taken on overflow and underflow.
- Whether
doubletofloatrounds or truncates. - Whether right-shifting a signed value is an arithmetic or logical shift.
- Order of evaluation of operands and function arguments.