Types and operators

C Provides a set of minimal basic data types, refered to as primitive data types.

Integral Types

  • char : 8 bit (1 byte) ASCII character -> S: -128..127, U: 0..255
  • short : 16 bit small integer -> S: -32768 - 32767
  • int : 16-32 bit Default integer -> “Most comfortable size”
  • long : at least 32 bit, some compilers support long long for 64 bits

These types can all be preceded by the qualifier unsigned which dissallows representing negative numbers, doubling the positive number representable.

Literals

By default literals in C are ints. One can express a long literal by adding L to the end. ie - 42L. You can exprecc an octal number by preceding it with 0 ie - 012 is 10.

Combinations/Promotions

Integral types can be mixed with arithmetic operations.

('b' + 5)

The char (8 bit) will be promoted to the size of the larger type (the int) before the values are combined.

There is no infomration loss in the promotion process as the smaller type will always get promoted to the larger type.

Floating point types

  • float : Single precision floating point number 32 bits
  • double : Double precision floating point number 64 biths
  • long double : Obscure big floating point number

Most programmers use doubles. Floats should only be used when trying to save memory.

Also never use equality == to compare floating point numbers. Only use <

Declaration and Assignment

One can declare a variable in C in the following format

type_name identifier_name;
or
type_name identifier_name = value;

Where the = value is the optional assigment cluase.

Truncation

This is the opposite of promotion. Truncation moves a value from a type to a smaller type. The compiler will drop the extra bits.

char ch;
int i;

i = 321;
ch = i;
// ch is now 65

Note: The assigment will drop the uper bits of the int 321. The flower 8 bits of the number represents the number 65 (321-256). So the value of ch will be (char)65 which is ‘A’.

This will also occur across floating/integral types.

double pi;
int i;

pi = 3.14159;
i = pi;
// i is now 3

Boolean

There is no boolean type in C. Instead use an int. C will treat a 0 as false and all non zero values as true

Example

int i = 0;
while(i - 10) {

Mathematical operations

C has your typical mathematical operations

  • +
  • -
  • /
  • *
  • %
  • var++
  • ++var

Comparison operations

C has your typical comparison operations

  • ==
  • !=
  • >
  • <
  • >=
  • <=

Logical operations

C has your typical logical operators

  • || or
  • && and
  • ! not

Bitwise operations

C includes operators to manipulate memory at the bit level. This is useful for low level code.

  • ~ Bitwise Negation – flip 0 to 1 and 1 to 0
  • & Bitwise And – 1111 & 1001 = 1001
  • | Bitwise or – 1101 1001 = 1101
  • ^ Bitwise exclusive or
  • >> Shift by right /2
  • << Shift by right *2
Written on September 15, 2017