% cobbled by Orna Agmon from Orr Dunkelman's HAIFUX slides 
\documentclass[a4]{seminar}
\special{! TeXDict begin /landplus90{true}store end } 
\usepackage{slidesec}
\usepackage[dvips]{graphicx}
\input{seminar.bug}
\input{seminar.bg2} 
\usepackage{fancyhdr}

\newcommand{\heading}[1]{\begin{center}\large\bf #1\end{center}}
\newcommand{\bold}{\bf}
\fancyhf{} % Clear all fields
\fancyhead[L]{\small Orna Agmon}
\fancyhead[R]{\small ladypine@vipe.technion.ac.il}
\fancyfoot[L]{\tiny\thedate}
\fancyfoot[C]{\small C Without a Spoon}
\fancyfoot[R]{\tiny Slide \theslide}
% To avoid that the headers be too close of the top of the page
\renewcommand{\slidetopmargin}{2cm}

\newcommand{\tex}{\TeX{}}
\newcommand{\latex}{\LaTeX{}}
\newcommand{\bslash}{\mbox{$\backslash$}}

% To center horizontally the headers and footers (see seminar.bug)
\renewcommand{\headwidth}{\textwidth}

% To adjust the frame length to the header and footer ones
\autoslidemarginstrue
%\twoup[2]
	
\begin{document}
\pagestyle{fancy}

%%%%%%%%%%%%%%%%%%%%% Title
\begin{slide}	
%\includegraphics{tux.eps}
\center{\Large { C Without a Spoon }}
\center{Orna Agmon} 
%\center{ladypine@vipe.technion.ac.il}
%\center{}
\end {slide}

\begin{slide}
\slideheading{Program of the Course}
\begin{itemize}
\item About 8 units of course, with intervals of about a week.
\item Within each unit, in the proper places, are interlaced Homework
questions and exercises.
 Those will be discussed at the beginning of the next unit.
Homework programs will be shown at the beginning of the next class,
 and discussed.
\item References:
\begin{itemize}
\item The C programming Language, second edition, Kernighan and Ritchie, has
the final word, and is the place to look for answers.
\item man / info on a Linux system
\end{itemize}
\item NOT everything will be explained in class - you will need to search for
some more information in the book or man pages.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{TOC}
\begin{itemize}
\item Why C?
\item C basics and Concepts
\item CPP
\item gcc compilation switches
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{What is C?}
\begin{itemize}
\item A procedural language
\item Compiled (not interpreted)
\item No Garbage Collection - programmer maintains memory.
\item CaSe SenSiTIvE != case sensitive
\item Used as a basis for C++.
\item Developed by Brian Keringham and Dennis Ritchie,
 when they needed a language to write
UNIX with (was written in B)
\item Can be linked with Fortran
\item C gives you enough rope to hang yourself with.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Why C?}
\begin{itemize}
\item Efficient - translates to machine language, no virtualization.
\item Stable - Linux Kernel is based on it.
\item Portable
\item Has standards, many compilers including free ones.
\item Strong checks, in many levels : Quality assurance.
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{C standards}
\begin{itemize}
\item ISO C ({\bf ANSI C}) since 1989. Widely supported, hence
preferred standard.
\item K\&R (the first book on C by Kernighan and Ritchie) C. Old Standard. The
book : The C programming language.
\item C9X. Not widely supported by compilers.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Flow of a C Program}
\begin{itemize}
\item A sentence ends with a semi-colon (;).
\item New lines do not matter
\item Still, it is more readable to break the lines at about 80 characters,
though not compulsory.
\item /* Comments must begin and end - Homework: 
think of a program that compiles, but produces the wrong executable, because of
an unclosed comment*/
\item //If the compiler is a C++ compiler, One liner comments are also valid.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Indentation and Syntax Highlighting}
\begin{itemize}
\item Proper indentation helps reading structured programming.
\item They are both done in good programming editors 
(emacs, xemacs (using tab), vi and others. Not pico.)
\item Going over the program and indenting it helps finding blocks which were
not properly closed.
\end{itemize}
\end{slide}




\begin{slide}
\slideheading{Basic Variables}
\begin{itemize}
\item Variables have some basic types: char, int, short, double, float.
\item For logical variables use an integer-like variable.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Logical Operators}
\begin{itemize}
\item Over variables: \begin{verbatim} < > == != || && \end{verbatim}
\item Binary operations: \begin{verbatim} | & \end{verbatim}
\item Unary operation: \verb+!+
\item unrelated note: for $a^b$, use pow(a,b), and add the line 
\verb+#include <math.h>+ at the top.
\end{itemize}
\end{slide}



\begin{slide}
\slideheading{Blocks}
\begin{itemize}
\item An execution block is a single statement or a group of statements,
enclosed by curly braces: \{\}. For example, an ``if'' statement, with and
without blocks:
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Blocks With and Without Curly Braces}
\begin{itemize}
\item
\begin{verbatim}
if (a<5) 
    b=3;
else
    b=2;\end{verbatim}
\item
\begin{verbatim}
if (a<5) {
    b=3;
    b=3;/*I can add more statements here*/
} else {
    b=2;
}\end{verbatim}
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Where to put the new line?}
\begin{itemize}
\item Even though C permits writing all the code in one line, it is good to go
to a new line after an ``if'' or ``else'', for debugging purposes.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Ternary If}
\begin{itemize}
\item The same code can be written as: 
\begin{verbatim}b=(a<5)?3:5;\end{verbatim}
\item Useful for initializations and clarity of code.
\item Homework: write an expression that gives the minimal of the values a,b,
using ternary if and regular if. 
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Short-circuit Evaluation}
\begin{itemize}
\item \begin{verbatim}if ((a>0.0) && (sqrt(a)<5.0))
	 b=3;\end{verbatim}
\item sqrt is not allowed non-positive input, but it will never be evaluated.
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Do/While Loops}
\begin{itemize}
\item \begin{verbatim}
int i=0;
while (i<10) {
    ++i; 
}\end{verbatim}
\item \begin{verbatim}
int i=0;
do {
    ++i;
} while (i<10);\end{verbatim}
\item What is the difference?
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{The for loop}
\begin{itemize}
\item 
\begin{verbatim}
int i,N=10;
for (i=0;i<N;++i){
    /*execution block*/	
}
\end{verbatim}
\item 3 clauses in the parenthesis: initialization, a condition for keeping on
the loop, and something to do when going to the next cycle.
\item Within the block, comes the actual code to be executed.
\item The loop variable must be declared before the loop, otherwise the
behavior is not well defined (C++ extension).
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Break and Continue}
\begin{itemize}
\item \verb|int i,j=0;for (i=0;i<10;++i){ if (i<5) continue; ++j;}|
\item \verb|int i,j=0;for (i=0;i<10;++i){ if (i<5) break; ++j;}|
\item What is the value of j?
\item What is the value of i?
\item What is wrong with this question?
\item Note the obfuscated c in the examples. Bad formatting!
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Switch}
\begin{verbatim}
switch (i){
case 1:
    a=3;
    break;
case 2:
    a=3;
    break;	
case 213124:
    a=-1;
    break;
default:
    a=-1000;
}
\end{verbatim}
\begin{itemize}
\item The break prevents continuing to the next code line. 
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Falling Through a Switch}
\begin{itemize}
\item 
\begin{verbatim}
switch (i){
case 1:
    /*fall through!!*/
case 2:
    a=3;
    break;
case 213124:
    a=-1;
    break;
default:
    a=-1000;
}
\end{verbatim}
\item When collating options, add the comment /*fall through*/,
 to indicate intention.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{When to use a switch?}
\begin{itemize}
\item Used when there are many different options - a switch is more readable.
\item Used when there is a key, and there are only certain legitimate options.
 Using
enum (an integer with specific values only, see later), the code will not compile if the switch does not deal with
all possible values.
\end{itemize}
\end{slide}



\begin{slide}
\slideheading{go to label}
\begin{itemize}
\item \begin{verbatim}
if (bad_example!=0) 
    goto L1;
bad_example=1;
L1:   bad_example=0;
\end{verbatim}

\item Usually, it is wrong to use goto...
\item Except, when catching errors, and cleaning up (see later in dynamic memory)
\end{itemize}
\end{slide}




\begin{slide}
\slideheading{printf  - Simple Output}
\begin{itemize}
\item The function printf prints to STDOUT. 
\item It take an arbitrary number of parameters.
\item It gets a format and the values to print. Special characters must be
escaped. Homework: \verb+man 3 printf+.
\item \begin{verbatim}
printf(``one is %d, a third is %g'',1,1.0/3.0);
\end{verbatim}
\item Homework: What is the difference between 1/3 and 1.0/3.0? How much is 1/3.0?
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Hello World}
\begin{itemize}
\item \begin{verbatim}
#include <stdio.h>
int main(void){
    printf("Hello World\n");
    return 0;
}
\end{verbatim}
\item Copy the program to file hello\_world.c (can be copied from
/orna/lectures/c/examples)
\item Compile with \verb+gcc hello_world.c+. Run with \verb+a.out+.
\item Homework: Use the simple Hello World Program and the constructs
 discussed so far, to compute the square of the numbers 1 - 100.
for the square of 20, 30, 40 print 0.
 Implement once using if, and once using switch.
Bonus: print square roots. (man sqrt for the include, compile with -lm
for math library).
\end{itemize}
\end{slide}


%%%%%%%%%%%%%%%%%%%%% Title
\begin{slide}	
%\includegraphics{tux.eps}
\center{\Large { CPP - The C Pre Processor }}
\center{Orna Agmon} 
%\center{ladypine@vipe.technion.ac.il}
%\center{}
\end {slide}


\begin{slide}
\slideheading{The Pre Processor}
A utility (/usr/bin/cpp) which goes over the C source files, combining code
snippets into coherent files. Its purpose is:
\begin{itemize}
\item Make sure that code pieces are
written exactly the same way all over the program.
\item Macros
\item Have code in the source file without seeing it.
\item Exclude source from the file, pending on switches.
\item Prevent bad compilation and linkage
\item Portability
\item Create several executables from the same source
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{What does cpp actually do?}
\begin{itemize}
\item To see what the preprocessor does: \verb+gcc -E hello_world.c+, or
\verb+cpp hello_world.c+.
\item Try with -P for readability.
\item Homework: when is it better to use gcc -E?
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{The Basic cpp instructions}
\begin{verbatim}
#include <stdio.h>
#include ``action.h''
#define PROGRAM_VERSION 10
#undef PROGRAM_VERSION
#ifdef  PROGRAM_VERSION
#ifndef  PROGRAM_VERSION
#if !defined(PROGRAM_VERSION)
#endif
\end{verbatim}
\end{slide}

\begin{slide}
\slideheading{The Include Path}
\begin{itemize}
\item When given a file in an \#include command, 
cpp searches for it at a given path - the include path.
\item The include path includes system directories, such as /usr/include and
its subdirectories.
\item System and compiler include paths differ on different systems. (Use
autoconf to set them)
\item When using quotation marks, the include path begins with the current directory.
\item Additional directories can be added using the -I switch.
\item Pre Processor switches can be given to the compiler - it passes them to
the Pre Processor.
\begin{verbatim}
gcc -I/home/orna/include/ hello_world.c
\end{verbatim}
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Choosing The Include Path}
\begin{itemize}
\item HomeWork: How do you choose between include with ``'' and with \verb+<>+?
\item What can happen if you get it wrong?
\end{itemize}
\end{slide}



\begin{slide}
\slideheading{Protecting Headers}
\begin{itemize}
\item A header is a file, 
which contains the prototypes of functions. Typically, the file's name ends
with .c, and the compatible header's name is the same, only with a .h suffix.
\item A proper header must contain all the information required to
 define those prototypes.
\item To avoid multiple definitions, use the following form (in this example,
for a header called myheader.h)
\begin{verbatim}
#ifndef MYHEADER_H
#define MYHEADER_H
/* Here comes the header for function myheader itself*/
void myheader(void);
#endif
\end{verbatim}
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Protecting Headers Safety}
Homework: What happens if you sometimes write in the format \#ifndef
MYHEADER\_H, and some other times, in the format MYHEADER\_DEFINED?
\end{slide}

\begin{slide}
\slideheading{Definitions}
The scope of the definition is the syntactic scope from this point on, in the
same file.
\begin{itemize}
\item Example: 
 \begin{verbatim}
#define PAI PI_M
#define PAI 3.14
#define EPSILON 1.e-10
#define SIZE_OF_ARRAY 100
#define malloc mymalloc
#define MY_NEW_MACRO_APPROVED
#define DEBUG_MODE
\end{verbatim}
\item to make sure the same constants are used throughout the program
\item to enable quick changes of sizes.
\item to set a size of an array, which needed at compile time.
\item to trick the compiler, by replacing a library function with another,
local, function. Note
that in such a case, the definition must not appear before the definition of
the function.
\end{itemize}
\end{slide}



\begin{slide}
\slideheading{Homework - Replacing a Function}
\begin{itemize}
\item Use \#define to make the program (written in previous Homework),
which prints square roots, print
squares instead.
\item Use the following function (/orna/lectures/c/examples/square\_function.c):
\begin{verbatim}
double square(const double a){
    return a*a;
}
\end{verbatim}
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Macros}
\begin{itemize}
\item A bad example for a macro definition:
 \begin{verbatim}#define MIN(A,B) A<B?A:B\end{verbatim}
\item A good example: 
\begin{verbatim}#define MIN(A,B) (((A)<(B))?(A):(B))\end{verbatim}
\item Using a macro:\begin{verbatim}i=MIN(3,5);\end{verbatim}
\item Macros may also be protected, to avoid re-definition:
\begin{verbatim}
#ifndef MIN
#define MIN(A,B) (((A)<(B))?(A):(B))
#endif\end{verbatim}
\item Homework: Bring an example where using the MIN macro is dangerous, and
has unwanted side-effects.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{MACROS are problematic}
\begin{itemize}
\item Complicated macros can be created using continuation lines:
\begin{verbatim}
#define MIN(A,B) \ 
         (((A)<(B))?(A):(B))
\end{verbatim}
\item But: You cannot debug inside a macro!
\item It is hard to tell when compiler errors come from within a macro.
\item Indentation of a macro is not automatically done by IDEs.
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Stringification}
\begin{itemize}
\item an argument preceded by a \# is expressed literally.
\begin{verbatim}
     #define WARN_IF(EXP) \
     do { if (EXP) \
             fprintf (stderr, "Warning: " #EXP "\n"); } \
     while (0)
\end{verbatim}
\item The do-while are there to make it possible to write WARN\_IF(ARG);
\item Homework: info CPP (more updated than the man page). This example and the
next are from info cpp.
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Concatenation}
\begin{verbatim}
     struct command
     {
       char *name;
       void (*function) ();
     };
     
     struct command commands[] =
     {
       { "quit", quit_command},
       { "help", help_command},
       ...
     };

\end{verbatim}
Instead:
\begin{verbatim}
     #define COMMAND(NAME)  { #NAME, NAME ## _command }
     
     struct command commands[] =
     {
       COMMAND (quit),
       COMMAND (help),
       ...
     };

\end{verbatim}
\end{slide}

%%%%%%%%%%%%%%%%%%%%% Title
\begin{slide}	
%\includegraphics{tux.eps}
\center{\Large {The Compiler}}
\center{Orna Agmon} 
%\center{ladypine@vipe.technion.ac.il}
%\center{}
\end {slide}


\begin{slide}
\slideheading{Compilers}
\begin{itemize}
\item C compilers are available on most UN*X machines. 
\item The free C compiler is gcc.
\item gcc is widely available over various platforms.
\item The compiler we use defines the meaning of the C we write, because
compilers differ in the implementation.
\item Some compilers do not comply with some standards,
some enlarge the language with specific features.
\item Strict C rules ensure that the program will compile on many compilers.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{gcc Compilation Switches}
Switches follow the compiler's name with a ``-'' in the command line. For example:
\begin{itemize}
\item Language Options: -ansi 
\item Warning Options: -Wstrict-prototypes -Wmissing-prototypes
-Wpointer-arith -Wcast-align -Wimplicit -Wmain -Wswitch
-Wformat-Wchar-subscripts -Wreturn-type -Wcast-qual -Wcast-align
\item -pedantic - do not use gcc extensions
\item -Wshadow 
\item -Wunused
\item -Werror
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{More gcc Compilation Switches}
\begin{itemize}
\item Question: what does -Wall do? Compare $(0==a)$ to $(a==0)$ to $((a=0))$. compare\_asign.c
\item definitions: -Dmacro=def, -Dmacro : define a macro all over the program.
\item Profiling: -pg
\item Debugging: -g
\item output: -o targetname
\item linkage: -c
\item Optimization: -O, -O0, -O1, -O2, -O3, -finline-functions, -ffloat-store
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Homework - gcc switches}
\begin{itemize}
\item Read the section in gcc man page about Warning options, and
specifically check
what the above mentioned options do.
\item Write a program which prints your name, only if macro YOUR\_INFO is
defined. Compile it twice from the same source, and run.
\item Change the program such that is prints A,B,C, if YOUR\_INFO equals 1,2,3
respectively, compile and run in various methods.
\item Between the last two exercises, which was intended to use \#ifdef?
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{gcc Extensions}
Many gcc extensions are nowadays acceptable in many other compilers.
Read all about gcc extensions under info gcc, C extensions.
\begin{itemize}
\item inline functions
\item c++ comments
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Profiling with gprof}
\begin{itemize}
\item Compile with optimization data using -pg. Use file the\_third\_rule.c.
\item Run the executable (a.out). A file called gmon.out will be created.
\item Run \verb+gprof a.out+ to get a report on the performance.
\end{itemize}
\end{slide}



%%%%%%%%%%%%%%%%%%%%% Title
\begin{slide}	
%\includegraphics{tux.eps}
\center{\Large {Variables}}
\center{Orna Agmon} 
%\center{ladypine@vipe.technion.ac.il}
%\center{}
\end {slide}

\begin{slide}
\slideheading{Variable Declarations}
\begin{itemize}
\item Variables are always declared at the beginning of a block (in C++, they
can be declared anywhere within the code)
\item Variables inside functions have a lexical scope they are valid in.
\item Global variables (use only when must!) have a syntactic scope they are
valid in.
\item Best to declare variables as close (syntactically) 
	to where they are used.
\item Best to initialize variable when declaring them. An initialization can be
done with constant values only. gcc extention: runtime values as well. 
\item Best to declare variables in the smallest lexical scope.
\item Variables may shadow each other - avoid this (-Wshadow)
\item Unused variables and parametersmay indicate a bug 
(-Wunused: parameter,variable,value)
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Built in Types}
\begin{itemize}
\item Built-in variables: float, double, char, int, long, long long (not always
supported).
\item C types specify minimal sizes only: int is at least 16 bit, long
is at least 32 bit.
\item Short is least 8 bit, but will still be so on 64bit architecture (too
many things rely on this).
\item gcc extention - an integer with defined number of bits:
\verb+ unsigned int foo:1+ for logical.
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{enum - a self generated type}
\begin{itemize}
\item enum is a way to give integer values a literal meaning
\item \begin{verbatim}
enum key_function_e{
    KEY_FUNCTION_NONE=0,
    KEY_FUNCTION_CONST=1,
    KEY_FUNCTION_CONSTANT=1,
    KEY_FUNCTION_LINEAR,
    KEY_FUNCTION_CUBIC,
    KEY_FUNCTION_TRIANGULAR
}key_function;
\end{verbatim}
\item Enum values are set from 0 on, unless forced.
\item Enum values are global - best to use a common initial to all enum values
of the same variable. 
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Enum - cont.}
\begin{itemize}
\item Enum values may be added in time - best not to rely upon their numeral
value. If must, make a comment on the definition, and explicitly set the
values.
\item An enum value can be printed as an integer. To print it as a string you
must write a function per each enum.
\item z e2s.pl will create for you a file with functions which work both ways:
converting enums to strings and strings to enums. 
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{typedef}
\begin{itemize}
\item \begin{verbatim}
typedef enum key_function_e{
    KEY_FUNCTION_NONE=0,
    KEY_FUNCTION_CONST=1,
    KEY_FUNCTION_CONSTANT=1,
    KEY_FUNCTION_LINEAR,
    KEY_FUNCTION_CUBIC,
    KEY_FUNCTION_TRIANGULAR
}key_function_t;

key_function_t key_function1, key_function2;
\end{verbatim} 
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{typedef - cont.}
\begin{itemize}
\item It is useful to define a new type when:
\begin{itemize}
\item The type definition is complicated
\item A variable typed thus is passed into a function, and you want to change
its const attribution.
\item Generalization and architecture independence: 
Usage of special types will insure consistency with system
libraries: {\bf size\_t} for sizes, {\bf time\_t} for the return value
of the {\bf time} function.
\end{itemize}
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Arrays}
\begin{itemize}
\item An array of integers:\verb+int a[100];+
\item Access to an array is done using square brackets: a[0] is the first
element.
\item A multidimensional double array: \verb+double b[10][34][20];+
\item A multidimensional array is arranged in the memory such that b[i][j+1]
follows exactly after b[i][j] (opposed to Fortran arrays).
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Strings}
\begin{itemize}
\item A string is an array of char variables: \verb+char mystr[80];+
\item A C string is NULL terminated: after the last significant character
comes the character \verb+'\0'+, whose value is really 0000000 in binary.
\item C functions which work on strings are found in string.h.
\item Homework: man snprintf, compare to  sprintf. man strncat, strncmp,
strncpy, strlen. When is strcpy usefull?
\item Note the confusing return value of strncmp.
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Pointers}

\begin{itemize}
\item Each named variable is a nickname for an address in the memory.
\item \verb+&a+ is the address of the variable a. The size of the number
depends on the architecture - on a 64bit arch it will be a 64bit number.
\item \verb+ int *b=&a+ :a variable defined as a pointer to a type can hold its
address.
\item Refer to the value in the address held in a pointer using *: \verb+*b+
will give the value stored in variable a, even if a is set to a new value.
\item Pointers have an alignment: a pointer for a small data type may be an
invalid pointer for a larger data type.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Casting}
\begin{itemize}
\item Casting is converting variables between types.
\item An implicit casting is done for example when using sqrt(i), where i is
int. Also when computing a mixed formula with integers and doubles, or when
setting its output into an integer.
\item \verb+int i=1.0/3.0;+
\item \verb+double i=1/3.0;+
\item Usually casting is dangerous.
\item Because of pointer alignment, pointer casting is extremely dangerous, and
may be unportable. For example, the space of
one 8-byte float will accommodate 4 2-byte int values on some system,
and 2 4-byte int values on others. 
\item Check using the program casting.c.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{struct}
\begin{itemize}
\item A struct holds together a collection of variables.
\item \begin{verbatim}
struct linear_function_s{
    double a,/* slope of line */
	double b;/* constant of line */
}linear_function;
\end{verbatim}
\item The order of the variables within the struct in the memory is according
to their order in the definition.
\item However, there may be gaps (padding) between the variables - according to
implementation.
\item Padding may be controlled by a compiler option.
\item A struct does not have to be named, but it helps debugging and makes
compilation checks possible.
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Copying a struct}
\begin{itemize}
\item For most variables, copying is done using  \verb+a=b+.
\item Structs may have gaps inside them. So using = may work, but is not
standard.
\item If you intend to copy a struct, initialize its memory before you fill
values in it:
\begin{verbatim}
memset(linear_function,0,
       sizeof(struct linear_function_s));
\end{verbatim}
Then copy all the memory using memset or bzero:
\begin{verbatim}
memcpy(linear_function1,linear_function2,
       sizeof(struct linear_function_s));
\end{verbatim}
\item Homework: man memcpy, memcmp,memset, bzero.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Parts of structs and pointers}
\begin{itemize}
\item \begin{verbatim}
struct linear_function_s linear_function, *ptr;
double c;
c=linear_function.a;
ptr=&linear_function;
c=ptr->a;
\end{verbatim}
\item An element of a struct is referred to using a period (``.'')
\item An element of a struct to which you have a pointer is referred to using
an arrow (``\verb+->+'');
\item The names of the parts of the struct are defined by its definition.
\item A struct can be named a name you like.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{A linked list}
A linked list is a data structure intended for dynamic growth, as well as a
dynamic change of order of the elements.
Though there can be many implementations, most of them use a struct:
\begin{verbatim}
typedef struct list_element_s{
    double payload;
    struct list_element_s *next;/*a must*/
    struct list_element_s *prev;/* may be needed*/
} list_element_t;
\end{verbatim}
Homework: Why did I not use the typedef here, but wrote three times the long
name of the struct?
\end{slide}




%%%%%%%%%%%%%%%%%%%%% Title
\begin{slide}	
%\includegraphics{tux.eps}
\center{\Large {Functions}}
\center{Orna Agmon} 
%\center{ladypine@vipe.technion.ac.il}
%\center{}
\end {slide}


\begin{slide}
\slideheading{Defining Functions}
\begin{itemize}
\item There are no procedures - only functions.
\item A function can have side effects, apart from the return
value. (procedural programming) 
\item A function is defined by its input (arguments) and by its output (return
value):
\begin{verbatim}
int square(int a, int to_print){
    int b=a*a;
    if (to_print)
    printf(``%d\n'',b);
    return b;
}
\end{verbatim}
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Return Value}
\begin{itemize}
\item A function can have side effects. 
\item A function can return a void, which means it does not return a value.
\item The return value of a subroutine can be used as a flag for
failure. ``Success has many parents, but failure is an orphan''. Still, success
has little info to pass, and failure can be caused due to many reasons.
 Hence, 0
is used for success, non-0 for failure. In cpp implemented using throw/catch.
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Static Functions}
\begin{itemize}
\item To define a function only in syntactic scope of the same file, use
static:
\begin{verbatim}
static int square{int a, int to_print};
\end{verbatim}
static functions cannot be profiled - use a macro instead.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{ System calls and Library functions MAY FAIL}
\begin{itemize}
\item System calls are system functions - to communicate with the operating
system
\item Homework : write a program which removes a file in two ways: 1.using
the unlink system-call, 2. using system. Man system, unlink. 
\item Library functions are functions supplied by the c language or other
packages. For example, the math library supplies sin, cos.
\item The return value of system calls must always be checked, for the program
to be robust.
\item Find about the return values at the end of the man/info page. 
\item Homework: read man page and find return values for examplatory 
functions for example: fopen, fclose.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{errno}
\begin{itemize}
\item System calls and some library functions set a variable called errno
 when they have a problem, to state the
type of problem.
\item Usually, when a system call fails, it sets errno to negative value.
\item A succesful library call is allowed to change the value of errno.
 (After a successful call, errno is undefined).
\item If -1 is a legitimate value of the syscall, it may be necessary to
initialize errno with 0, to know if it failed.
\item strerror translates the error code to a string. perror prints it.
\item Homework : man errno, strerror, perror.
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Prototypes}
\begin{itemize}
\item A prototype resembles the definition of the function, only with a
semi-colon at the end:
\begin{verbatim}
int square(int a);

int square(int a){
    return a*a;
}
\end{verbatim}
\item The prototype is usually placed at the header file.
\item If the file which includes the function includes the header as well, the
compiler can verify they match.
\item Then any other code which uses the function can rely on the header for
accurate usage.

\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Homework - Multiple files in a project}
\begin{itemize}
\item Write a program with two files. In each file is a function. The main
function calls a function in the other file.
\item Compile using a standard portable makefile, using the following
prodedure:
\begin{itemize} 
\item Have configure.in, makefile.in in the directory (you can copy from an
existing program).
\item autoconf
\item bring needed scripts for configure (it will complain specifically if you
do not)
\item configure
\item make
\end{itemize}
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Const, Addresses and  Values}
Using const on a parameter or a part of it means that
 the code will not compile
if the function tries to change the constant part.
\begin{itemize}
\item Pass by value:
\begin{verbatim}
int square{int input};
int square{const int input};
\end{verbatim}
\item Pass a pointer to value:
\begin{verbatim}
int square{int *input};
int square{int * const input};
\end{verbatim}
\item A variable may be declared const within a function, and be used instead
of a \#define-ed value. (It has a lexical scope just like a regular variable).
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Passing a pointer}
\begin{itemize}
\item Inside the function, *input is the value itself.
\item input is the address of the value.
\item \verb+*input=5;+ will actually set the variable outside the function.
\item \verb+input=NULL;+ will set the address inside the function,
 but will not affect what happens outside.
\item When using const and trying to change the value inside the function 
it will not compile. When not using const, it may cause a bug. 
\item In order to pass the adress of variable b to a function, pass \&b.
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Const - Homework}
\begin{itemize}
\item Write a program in which you attempt to change a variable which
is passed by value.
\item  Print its value at the end of the function.
\item  Print its value outside the function.
\item  Write a program in which you pass a const value and
try to change it in the function, and
compile it. What happens?
\end{itemize}
\end{slide}


%%%%%%%%%%%%%%%%%%%%% Title
\begin{slide}	
%\includegraphics{tux.eps}
\center{\Large { Dynamic Memory}}
\center{Orna Agmon} 
%\center{ladypine@vipe.technion.ac.il}
%\center{}
\end {slide}

\begin{slide}
\slideheading{Memory Areas}
\begin{itemize}
\item Stack - ordered according to order of access into functions. If the
language allows for recursive functions (like C), each function entrance is on
another place on the stack. C stack is rather small compared to fortran, and
platform dependent - place your big arrays some place else! (If you do not, you
may overrun your stack pointer). Size of arrays must be known at compile time.
\item DATA - Global variables
\item Heap - Random access, according to available memory at the moment of
request. Size of arrays may be only known at some point on run time. Place your large arrays here! 
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Dynamic Allocation}
\begin{itemize}
\item malloc requests memory from the heap. free returns it.
\item Homework: man free, alloc, realloc.
\item Naive allocate and free:\begin{verbatim}
int *a=(int *)malloc(4*sizeof(int));
a[3]=3;
free(a);
\end{verbatim}
\item Why Free at all? (compare and contrast to garbage collection)
\item Allocation does not always succeed. Nor does Free. When can they fail?
Why?
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Clever Allocation}
Code according to Nadav Har'El.
\begin{verbatim}
void * my_alloc( const size_t size){
    void *mem;
    if(size<=0){
        printf ("Invalid attempt to allocate zero bytes");
        abort();
    }
    if(!(mem=malloc(size))){
        printf ("Allocation failed");
        abort();
    }
    return mem;
}
\end{verbatim}
\end{slide}


\begin{slide}
\slideheading{Clever Free}
Code according to Nadav Har'El.
\begin{verbatim}
void my_free(void ** const pointer){
    if(*pointer==NULL){
        printf("Invalid attempt to free a NULL pointer");
        abort();
    }
    free(*pointer);
    *pointer=NULL;
}
\end{verbatim}
\end{slide}

\begin{slide}
\slideheading{Usage of clever dynamic memory management}
\begin{itemize}
\item Use a macro to replace all your memory allocation calls:
\begin{verbatim}
#define myvalloc(ptr,type,nelem) \
((ptr)=(type*)myalloc((nelem)*sizeof(*(ptr))))
\end{verbatim}
\item Homework: 
write a program which allocates and frees memory using the previous
code.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Memory Violations}
\begin{itemize}
\item Memory smear - reading from an unintended and unrelated location,
 or worse - writing there.
\item Memory Leak
\item Read access to uninitialized memory
\item Should I free the program's memory upon exit?
\item Automatic tools help avoid those problems:
\begin{itemize}
\item valgrind on Linux on i386
\item third on OSF1 on alpha
\item zmalloc on all platforms - compiled with the code
\end{itemize}
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Private Memory Management via pointer arithmetics}
\begin{itemize}
\item 
\begin{verbatim}
const int n=10;
int *x=(int *)my_malloc(2*n*sizeof(int));
int *y=*x+n;
\end{verbatim}
\item What is good about it, what is bad? (relate to memory fragmentations,
memory violation, efficiency)
\item How should this memory be freed?
\item What is y[0] if x was freed?
\item What happens if we free y?
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Memory fragmentation and the Intervals tree}
\begin{itemize}
\item The info about the heap is saved (in Linux) in the format of an interval
tree: a binary tree, where leaves on a node 
are kept as long as there is a difference in their status.
\item The intervals tree may be able to give small bits of memory, but not a
large piece, if the memory is fragmented.
\item The intervals tree may be better at uniting free memory than your
program.
\item Manage the memory only when you have a good reason to
 believe you know better.
\end{itemize}
\end{slide}

%%%%%%%%%%%%%%%%%%%%% Title
\begin{slide}	
%\includegraphics{tux.eps}
\center{\Large { Good Programming and Advanced Programming}}
\center{Orna Agmon} 
%\center{ladypine@vipe.technion.ac.il}
%\center{}
\end {slide}


\begin{slide}
\slideheading{Efficiency}
\begin{itemize}
\item Profiling will clear the big messes, but not the small ones.
\item Mis-concept: computation is slower than memory access
\item Current fact: memory access is the bottle-neck of high performance 
computing.
\item Hence, do not try storing small parts of calculations only because you
use them twice.
\item However, do store them in meaningfully named variables,
 if it helps readability. 
\item The compiler can optimize such things.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Cache misses}
\begin{itemize}
\item The cache is a fast small memory, located close to the CPU or in it.
\item Memory access is ``cheap'' when the data is already  in the cache.
\item When a line is brought to the cache, more data than the variable you
asked for is brought to the cache. (near data)
\item When designing a program, it is worth considering how to have minimal
cache misses: work for a long time on the same piece of data, instead of going
over arrays, and throwing everything from the cache right after.
\item valgrind can profile cache misses.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Documentation - What Goes Where?}
\begin{itemize}
\item Document exactly once: double documentation calls for contradictions.
\item The documentation of the general behavior of the function comes in the
header file, near its prototype. Describe its input and output and its general
usage. Intended for users of the function.
\item Before the implementation of the function, describe its general
algorithm. Intended for people who read the code (possibly briefly).
\item When documenting the code itself, avoid obvious statements (increasing i
by 1). 
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Documentation - How?}
\begin{itemize}
\item 1:1 is considered a fair documentation: code ratio
\item Do not fear to leave empty lines for readability.
\item Doxygen generates an html help from comments in the code. This prevent
the need to document twice.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Debugging}
\begin{itemize}
\item Print to a file, to the screen (STDOUT) or to the standard error (STDERR)
- printf, fprintf
\item WARN\_IF macro
\item abort() - to dump a core, and later debug using a picture of the memory
as it was the the violation was commited (use gdb -c core to see it)
\item IEEE functions: isnan, isinf, isalpha etc. They consider locale.
\item Every command begins on a new line, to enable breakpoints.
\item Code which is excluded using macros should be compiled on its own, is
possible, to be able to check every combination of macro switches.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Debuggers}
\begin{itemize}
\item -g for debug symbols
\item valgrind --gdb\_attach=yes to attach to the process when a emmory
violation was commited.
\item Debuggers: \begin{itemize}
\item gdb (and graphic ends: ddd, xgdb)
\item ladebug (and a graphic end: xladebug)
\item dbx
\end{itemize}
\end{itemize}
\end{slide}



\begin{slide}
\slideheading{Linking Fortran and C - matching variables}
\begin{itemize}
\item Fortran actually accepts pointers to variables - this is how in Fortran,
variables can be changed inside the function.
\item When Fortran needs to get $integer*4$, or an array of it, 
 C can pass \verb+int *+, on
architectures where int is 32 bit.
\item When Fortran needs to get $integer*2$, or an array of it, 
 C can pass \verb+short *+, on
architectures where short is 16 bit.
\item When Fortran gets $real*8$, or an array of it, 
C passes \verb+double *+.
\item When Fortran gets $real*4$, or an array of it, 
C passes \verb+float *+.
\item When Fortran needs to get $integer*4$, C needs to pass \verb+int *+.
\item Multidimensional arrays are held transposed. If Fortran needs A(3,4),
 C needs to passes A[4][3] (multidimensional array - not pointer to pointer!).
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Linkage}
\begin{itemize}
\item After compilation, every function/subroutine gets a symbol.
\item The symbol is not related to the name of the file in which the subroutine
was written.
\item The name is related in various ways to the subroutine's name.
\item When linking several languages, name-mangling may affect the programming:
The calling language may have to use a different name for the called function
than the name which was defined in the code.
 When using only one language, it has no effect.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Name Mangling}
\begin{itemize}
\item The other language's symbols usually have an underscore at their end. For
example, subroutine mysub in Fortran may be referred to as mysub\_.
\item Depending on the Fortran compiler, there may be a different treatment for
subroutine names wich include underscore inside them: they may get two
underscores at their end. For example, subroutine my\_sub
 in Fortran may be referred to as my\_sub\_\_.
\item Since Fortran is not case sensitive, it cannot tell the difference
between c functions which differ by caps. For example, if you have two c
functions, \verb+void myfunc(void)+ and \verb+void MYFUNC(void)+, and in the
Fortran code MyFunc\_ was called, which of the functions should be used?
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Name Mangling - Answer}
\begin{itemize}
\item The linker is activated by the compiler which compiled all the
objects to one executable. If the compiler is Fortran, it will refuse to link
two functions by the same name.
\item Homework: what if the compiler which calles the linker is C? (To check
this, create a main c function, which calls a fortran subroutine, which calls
MyFunc\_. Also compile two c functions, myfunc and MYFUNC.)
\end{itemize}
\end{slide}

 
\begin{slide}
\slideheading{Linking Fortran and C: Conclusions}
When a function is about to be called from another language:
\begin{itemize}
\item It must not include underscores.
\item It had better be all lowercase and have no confusables.
\item If it is Fortran, it cannot be get or return a logical (which C does not
support).
\item If it is Fortran77 it cannot get/return a pointer to pointer (which
fortran 77 does not support).
\item Still, there may be platforms where this is not enough and the code must
change in order to link in this particular environment. Define the functions
names as pre-processor constants at one place, to be able to replace them. For
example:
\begin{verbatim}
#define FORTRAN_MY_FUNC myfunc_
\end{verbatim}
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Design}
\begin{itemize}
\item Define constants using names, at one point
\item Prepare to add more variables to the module -it easy ans safe.
(for example: prefer allocating
an array of structs over allocating arrays within a struct)
\item Prefare interfaces that do not change when you add more variables to the
module: for example, use a struct which holds the data to the function.
\item string sizes should be fixed in one place
\item Verify interfaces at compile time, or else at link time or compile time.
\item Collect a (new) module's functions in one place.
 Within the existing code, add only calls to the new functions.
\end{itemize}
\end{slide}


\begin{slide}
\slideheading{Input}
\begin{itemize}
\item Separate code and data: 
Input should be read from files or from the command line - do not insert
it in the code itself.
\item When reading an input file, it should be self documented: for example,
read first the number of lines, and then you know how many lines to read. Do
not expect to get this data elsewhere. Better to have a mnemonic description of
the data inside the data file.
\item Save ASCII files, not binaries.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Command Line Input - Declaration}
\begin{verbatim}
#include <getopt.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
    char c;
    int int_after_t;
\end{verbatim}
\end{slide}

\begin{slide}
\slideheading{Command Line Input - Parsing}
\begin{verbatim}
    while((c = getopt(argc, argv, "nt:")) != -1){
        switch(c){
        case 'n':
            printf(``n was read\n'');
	    break;
        case 't':
            int_after_t=atoi(optarg);
	    break;
        default:
            printf("Usage:\%s [-n] [-t an_int]'',argv[0]);
            return -1;
        }
    }
\end{verbatim}
\end{slide}


\begin{slide}
\slideheading{Functions with a varying number of arguments}
\begin{itemize}
\item Useful for functions which print, like printf.
\item The function declaration contains ... after its list of regular
arguments, for example:
\begin{verbatim}
#include <stdarg.h>
void my_print(const char *format, ...){
    va_list args;
    va_start(args,format);/*Initialize the va_list,
           called with the last known parameter.*/
\end{verbatim}
\item The macro va\_arg(args, type) pops the next variable in the list.
\item va\_end(args) handles the return from a function which called va\_start.
Homework: man va\_start. Write a function which prints ints and doubles using a
format.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Function Pointers}
From man qsort:
\begin{verbatim} 
#include <stdlib.h>

void qsort(void *base, size_t nmemb, size_t size,
int(*compar)(const void *, const void *));
\end{verbatim}
Qsort expects a function pointer, to a function which receives two void
pointers and returns an integer.
\end{slide}

\begin{slide}
\slideheading{Using qsort}
\begin{verbatim}
int compare_ints(const void *a,const void *b);
int compare_ints(const void *a,const void *b){
    const int A=*(const int *) a;
    const int B=*(const int *) b;
    
    if(A< B) return -1;
    if(A==B) return  0;
    else return 1;
}
void sort_int(int *s,int n){
    qsort(s,n,sizeof(int),compare_ints);
    return;
}
\end{verbatim}
\end{slide}

\begin{slide}
\slideheading{Homework - Function Pointers}

\begin{verbatim} 
void myfunc(void){
    printf(``Hello World'');
    return;
}

int main(void){
    myfunc;
    myfunc();
    return;
}
\end{verbatim}
what will be printed? Why?
\end{slide}

\begin{slide}
\slideheading{Re-entrant functions}
\begin{itemize}
\item A function which does not save its status in global variables or static
variables is state-independent.
\item State-independent functions are re-entrant.
\item State independent functions can be used for recursion.
\item State-independent functions are safe to use with threads. State
independent design is easier to make parallelize later on, even if you do not
consider more CPUs right now.
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Recursion (recursion.c)}
\begin{verbatim}
#include <stdio.h>
static void recursive_print(const char * const str);
int main(void){
   recursive_print("Hello World\n");
   return 0;
}
static void recursive_print(const char * const str){
   if (str==NULL) return; 
   if (str[0]=='\0') return;
   printf("\%c",str[0]);
   recursive_print(str+1);
   return;
}
\end{verbatim}
\end{slide}


\begin{slide}
\slideheading{Programming Concepts}
\begin{itemize}
\item Procedural programming: the basic units are procedures: execution
units. return values are of lesser importance.
\item Functional programming: basic units are functions, with no side effects.
\item Object Oriented programming (OOP): basic units are variables.
 Variables can have functions to work on them
\end{itemize}
\end{slide}

\begin{slide}
\slideheading{Object - Oriented Concepts}
\begin{itemize}
\item Objects and their methods
\item Modularity
\item Encapsulation - access to private data of the object is limited, and done
by special methods.
\item Inheritance - the properties of an object can originate from properties
of a similar, less sofisticated object.
\end{itemize}
\end{slide}


%\begin{slide}
%\slideheading{}
%\begin{itemize}
%\item pointer to pointer as opposed to double array - maybe after teaching
%dynamic allocation.
%\item are const global varialbe there or are they replaced in compilation?
%\end{itemize}
%\end{slide}


%\begin{slide}
%\slideheading{}
%\begin{itemize}
%\item
%\item
%\end{itemize}
%\end{slide}

\end{document}

