Summary of the "C" language
Includes the ANSI STD features
Based on:
" C The Complete Reference " by Herbert Schildt, McGraw-Hill
" Standard C " by Plauger & Brodie
"American National Standard ANSI X.3.159-1998"
Note: Code comments are shown in red below for clarity.
Text between /* and */ are comments in C.
Program Structure:
The "main" function and one or more other functions may be in a file. There are
no procedures, a function may be used like a procedure with the function return
value, if any, just ignored. Files are compiled with the C compiler that can
produce an executable file.
Some typical file structures:
int main()
{
sequence_of_statements
return 0;
}
#include <stdio.h>
#include ... more header files from which definitions are needed global and/or external declarations and/or type definitions
int main()
{
local_declarations
sequence_of_statements
return 0;
}
void function_1( int i, double x, more_parameters )
{
local_declarations
sequence_of_statements
}
some_type function_2( void )
{
local_declarations
sequence_of_statements
return something-of-some_type;
}
#include <stdio.h>
global and/or external declarations
void main(int argc, char *argv[])
{
local_declarations
sequence_of_statements
}
Executable statements:
Statements end with a semicolon or brace. A compound statement may be made from
a sequence of statements by enclosing them in braces.
{ statement_1 ; statement_2 ; statement_3 ; }
is a statement but usually make code readable, one statement per line.
{ statement_1;
statement_2;
statement_3; }
Assignment statements:
x = 10;
x = x+1;
++x;
x++;
--x;
x--;
x = x+20;
x += 20;
x -= 20;
x *= 20;
x /= 20;
x %= 20;
x <<= 2;
x >>= 2;
x &= 20;
x ^= 20;
x |= 20;
x = (y=3,y++);
x = who ? 3 : y;
y = sin(x) ;
x = mat[i][j] ;
Function call with return ignored:
go_do_it();
exit(0);
Unconditional branches:
break;
continue;
return;
return exp;
goto label;
label: statement;
Conditional branching:
if ( condition ) statement ;
if ( condition ) statement ;
else statement_2 ;
if ( condition_1 )
if ( condition_2 ) statement ;
else statement_2 ;
if ( expression )
{
statement_sequence
}
else
{
statement_sequence
}
if-else-if ladder structure (must be space in 'else if')
if(exp_1)
statement_1;
else if(exp_2)
statement_2;
else if(exp_3)
statement_3;
...
else
statement_n;
Switch statement
switch ( expression )
{
case constant_1:
break;
case constant_2:
case constant_3:
statement_sequence
break;
case constant_4:
statement_sequence
case constant_5:
statement_sequence
break;
default:
statement_sequence
}
Iteration statements
for ( initialization ; condition ; increment ) statement ;
while ( condition ) statement ;
do
{
statement_sequence
} while ( condition ) ;
for(;;) statement;
while(1) statement;
in all iteration statements, break; causes an immediate exit from loop
continue; causes an immediate increment
Function definition:
Function Prototype
type function_name(type_1 var_1, type_2 var_2,...);
Function Definition
type function_name(int a, float b, const char * ch,...)
{ function_body }
char * strcpy( char * s1, const char * s2 ) { statements }
type function_name(a, b)
int a;
float b;
{ function_body }
example of a function and call passing the address of a scalar
void func(int *num)
{
*num *= *num;
} ...
func(&i);
Reserved words
Like everything else, must be lower case. (exactly 32 reserved words)
+---------------------------------------------------------------------------+
| term | Description |
|--------+------------------------------------------------------------------|
|auto |optional local declaration |
|--------+------------------------------------------------------------------|
|break |used to exit loop and used to exit switch |
|--------+------------------------------------------------------------------|
|case |choice in a switch |
|--------+------------------------------------------------------------------|
|char |basic declaration of a type character |
|--------+------------------------------------------------------------------|
|const |prefix declaration meaning variable can not be changed |
|--------+------------------------------------------------------------------|
|continue|go to bottom of loop in for, while and do loops |
|--------+------------------------------------------------------------------|
|default |optional last case of a switch |
|--------+------------------------------------------------------------------|
|do |executable statement, do-while loop |
|--------+------------------------------------------------------------------|
|double |basic declaration double precision floating point |
|--------+------------------------------------------------------------------|
|else |executable statement, part of "if" structure |
|--------+------------------------------------------------------------------|
|enum |basic declaration of enumeration type |
|--------+------------------------------------------------------------------|
|extern |prefix declaration meaning variable is defined externally |
|--------+------------------------------------------------------------------|
|float |basic declaration of floating point |
|--------+------------------------------------------------------------------|
|for |executable statement, for loop |
|--------+------------------------------------------------------------------|
|goto |jump within function to a label |
|--------+------------------------------------------------------------------|
|if |executable statement |
|--------+------------------------------------------------------------------|
|int |basic declaration of integer |
|--------+------------------------------------------------------------------|
|long |prefix declaration applying to many types |
|--------+------------------------------------------------------------------|
|register|prefix declaration meaning keep variable in register |
|--------+------------------------------------------------------------------|
|return |executable statement with or without a value |
|--------+------------------------------------------------------------------|
|short |prefix declaration applying to many types |
|--------+------------------------------------------------------------------|
|signed |prefix declaration applying to some types |
|--------+------------------------------------------------------------------|
|sizeof |operator applying to variables and types, gives size in bytes |
|--------+------------------------------------------------------------------|
|static |prefix declaration to make local variable static |
|--------+------------------------------------------------------------------|
|struct |declaration of a structure, like a record |
|--------+------------------------------------------------------------------|
|switch |executable statement for cases |
|--------+------------------------------------------------------------------|
|typedef |creates a new type name for an existing type |
|--------+------------------------------------------------------------------|
|union |declaration of variables that are in the same memory locations |
|--------+------------------------------------------------------------------|
|unsigned|prefix declaration applying to some types |
|--------+------------------------------------------------------------------|
|void |declaration of a typeless variable |
|--------+------------------------------------------------------------------|
|volatile|prefix declaration meaning the variable can be changed at any time|
|--------+------------------------------------------------------------------|
|while |executable statement, while loop or do-while loop |
+---------------------------------------------------------------------------+
Declarations have the forms
basic_type variable ;
basic_type variable_1, variable_2=value;
prefix_type(s) basic_type modifier_type variable_1, variable_2 ,... ;
type variable[val][val]...[val]={data,data,...};
struct struct_name {
type variable_1;
type variable_2;
...
type variable;
} variable_1, variable_2, ... ;
struct struct_name {
type variable_1: length;
type variable_1: length;
...
type variable_n: length_n;
} variable_1, variable_2, ... ;
struct struct_name more_variables;
union union_name {
type variable_1;
type variable_2;
...
type variable_n;
} variable_a, variable_b, ...;
union union_name variable ;
enum enum_type
{ enumeration_name_1,
enumeration_name_2=number,
...
enumeration_name_n
} variable, variable, ...;
enum enum_type variable;
enum enum_type variable = enumeration_name;
typedef existing_type new_type_name ;
Basic types
+---------------------------------------------------------------------+
| Type | Description |
|------+--------------------------------------------------------------|
|------+--------------------------------------------------------------|
|char |character type, usually one byte ( a string is array of char )|
|------+--------------------------------------------------------------|
|------+--------------------------------------------------------------|
|int |integer type, usually 2 or 4 bytes ( default ) |
|------+--------------------------------------------------------------|
|------+--------------------------------------------------------------|
|float |floating point type, usually 4 bytes |
|------+--------------------------------------------------------------|
|------+--------------------------------------------------------------|
|double|floating point type, usually 8 bytes |
|------+--------------------------------------------------------------|
|------+--------------------------------------------------------------|
|void |no type, typeless |
|------+--------------------------------------------------------------|
|------+--------------------------------------------------------------|
|enum |enumeration type ( user defines the type name ) |
+---------------------------------------------------------------------+
Type modifiers, prefix for basic types
+------------------------------------------------------------------------+
|Modifiers| Description |
|---------+--------------------------------------------------------------|
|---------+--------------------------------------------------------------|
|signed |has a sign ( default ) |
|---------+--------------------------------------------------------------|
|---------+--------------------------------------------------------------|
|unsigned |no sign bit in variable |
|---------+--------------------------------------------------------------|
|---------+--------------------------------------------------------------|
|long |longer version of type (short or long alone means short int or|
|---------+--------------------------------------------------------------|
|---------+--------------------------------------------------------------|
|short |shorter version of type long int because int is the default) |
|---------+--------------------------------------------------------------|
|---------+--------------------------------------------------------------|
|const |variable can not be stored into |
+------------------------------------------------------------------------+
Storage class, prefix for types
+----------------------------------------------------+
| Prefix | Description |
|--------+-------------------------------------------|
|--------+-------------------------------------------|
|auto |local variable ( default ) |
|--------+-------------------------------------------|
|--------+-------------------------------------------|
|static |permanent when function exits, not auto |
|--------+-------------------------------------------|
|--------+-------------------------------------------|
|volatile|can change from outside influence |
|--------+-------------------------------------------|
|--------+-------------------------------------------|
|extern |variables are defined elsewhere, externally|
|--------+-------------------------------------------|
|--------+-------------------------------------------|
|register|assign variable to register |
+----------------------------------------------------+
Modifier type
* makes variable a pointer
int i = 1000;
int *ptr;
ptr = &i;
*ptr = 100;
Samples of variable declarations
auto int xyz;
unsigned long int pqr;
extern int global_stuff, remote_function();
register int quick;
void just_do_it();
char * ch;
char * argv[];
struct account
{
char name[20];
float bal;
unsigned int sex:1;
} person;
struct account *p;
p=&person;
(*p).bal=100.00;
p->bal=100.00;
Automatic setting of array size based on data
char msg[]="Set the size to correct length \n";
char *p="auto length";
char ary[3]="Element in an array of messages";
float matrix[][3]={1.,2.,3.,4,.5.,6.};
float ***a;
Getting storage
int *p;
p=(int *)malloc(50*sizeof(int));
free(p);
Expressions:
1 to 32 characters including alphabetic,
variable names numeric and underscore
some_name ELSE Else z999
numbers integer and floating point like in FORTRAN
1 12345 .1 1. 1.5E-20
octal and hexadecimal
01777 0x248fff
long decimal, octal and hexadecimal
123456789L 017777777L oxFFFFFFFFL
single character between apostrophes plus
character special backslash codes
'a' 'Z' '\n'
characters between quotes plus special
string backslash codes a null is automatically
placed at end of every string
"Hello" "good by \n"
let exp, exp1, exp2, exp3 etc. stand for expressions
expressions are:
variables
numbers
characters
strings
unary_operator expression
expression binary_operator expression
( expression )
variable post_operator ( ++ and -- )
operator precedence and associativity is
highest
+------------------------------------+
|LR|( ) [ ] -> . x++ x-- |
|--+---------------------------------|
|RL|! ~ - + ++x --x * & sizeof (type)|
|--+---------------------------------|
|LR|* / % |
|--+---------------------------------|
|LR|+ - |
|--+---------------------------------|
|LR|<< >> |
|--+---------------------------------|
|LR|< <= > >= |
|--+---------------------------------|
|LR|== != |
|--+---------------------------------|
|LR|& |
|--+---------------------------------|
|LR|^ |
|--+---------------------------------|
|LR|| |
|--+---------------------------------|
|LR|&& |
|--+---------------------------------|
|LR||| |
|--+---------------------------------|
|RL|? : |
|--+---------------------------------|
|RL|= += -= *= /= %= >>= <<= &= ^= |=|
|--+---------------------------------|
|LR|, |
+------------------------------------+
lowest
LR means associate left to right, RL means associate right to left
This is why a = b = c = 1;
But int a,b,c = 1;
*p++ = -x->y;
operator definitions:
( ) grouping parenthesis, function call
[ ] array indexing, also [ ][ ] etc.
-> selector, structure pointer employee->wage = 7.50 ;
. select structure element employee.wage = 7.50 ;
! relational not, complement, ! a yields true or false
~ bitwise not, ones complement, ~ a
++ increment, pre or post to a variable
-- decrement, pre or post to a variable
- unary minus, - a
+ unary plus, + a
* indirect, the value of a pointer, * p is value at pointer p address
& the memory address, & b is the memory address of variable b
sizeof size in bytes, sizeof a or sizeof (int)
(type) a cast, explicit type conversion, (float) i, (*fun)(a,b), (int*)x
* multiply, a * b
/ divide, a / b
% modulo, a % b
+ add, a + b
- subtract, a - b
<< shift left, left operand is shifted left by right operand bits
>> shift right, left operand is shifted right by right operand bits
< less than, result is true or false, a %lt; b
<= less than or equal, result is true or false, a <= b
> greater than, result is true or false, a > b
>= greater than or equal, result is true or false, a >= b
== equal, result is true or false, a == b
!= not equal, result is true or false, a != b
& bitwise and, a & b
^ bitwise exclusive or, a ^ b
| bitwise or, a | b
&& relational and, result is true or false, a < b && c >= d
|| relational or, result is true or false, a < b || c >= d
? exp1 ? exp2 : exp3 result is exp2 if exp1 != 0, else result is exp3
= store
+= add and store
-= subtract and store
*= multiply and store
/= divide and store
%= modulo and store
<<= shift left and store
>>= shift right and store
&= bitwise and and store
^= bitwise exclusive or and store
|= bitwise or and store
, separator as in ( y=x,z=++x )
zero evaluates to false ( a null pointer has a zero value )
non zero evaluates to true ( !null_pointer is true )
* is heavily overloaded, so is &
Backslash codes for in character constants and strings
These can be used as characters when enclosed in apostrophies
\a alert, audible alarm, bell, ^G
\b Backspace, ^H
\f Form feed, new page, ^L
\n New line, carriage return and line feed, ^M^J
\o Octal constant, \oddd, \ddd
\r Carriage return, no line feed, ^M
\t Horizontal tab, tab, ^I
\v Vertical tab, ^K
\x Hexadecimal constant, \xdd 0 <= d <= F
\0 null, zero value character, ^@
\" Quote character
\' Apostrophe character
\\ Backslash character
\? Question mark character
\ddd Octal character value 0 <= d <= 7
Format commands for printf() scanf() fprintf(), fscanf() sprintf() sscanf()
%c a single character, char
%d a decimal number, int %hd is for short %ld is for long
%e a floating point number, float in scientific notation, %E for 1.0E-3
%le is for double, %Le is for long double
%f a floating point number with decimal point %10.4f 10 wide .dddd
%lf is for double, %Lf is for long double
%g a floating point number, %f or %e as needed, %G for capital E
%lg is for double, %Lg is for long double
%h an unsigned hexadecimal short integer (scanf only), old usage
%i an integer, int %hi is for short int, %li is for long int
%n pointer to integer to receive number of characters so far, int *i
%o an unsigned octal number, unsigned int %ho and %lo for short and long
%p a pointer, void **x
%s a string ( must be null terminated ! ), use %s for scanf
%u an unsigned decimal integer (printf only), unsigned int %hu %lu
%x a hexadecimal number, %X for capital ABCDEF, unsigned int %hx %lx
[...] string, x[]
% none
Text may be around format characters for printf(), The list follows the
single quoted format string.
Output is right justified unless format %-s or %-10.4f is used.
%+... causes plus sign to be printed.
%* suppresses assignment, no store, in scanf().
%# converts value to alternate form.
Field is expanded if not enough room to print.
numeric data into scanf() must be separated by space, tab or newline, not comma
characters between % in scanf() format must be in input and are ignored
Preprocessor directives:
#include "mine.h" search current working directory first
#include <stdio.h> search command line directory then system
#define TRUE 1 macro substitution, usually use capitals
#define min(a,b) (a<b)?(a): macro substitution with parameters
(b)
#define abs(a) (a<0)?(-(a)): macro substitution
(a)
#define note this comment gets inserted every time note
appears */
backslash \ at end of a line means continue
#undef TRUE undefines a previously defined macroname
#error stop compiling at this point
#if expression conditional compilation, start if structure
#elif expression else if expression != 0 compile following code
#else else compile following code
#endif end of conditional compiling
#ifdef macroname like #if, compiles if macroname defined
#ifndef like #if, compiles if macroname undefined
#line number [filename] set origin for __LINE__ and __FILE__
#pragma gives the compiler commands