C - Huji cse Moodle 2014/15

advertisement
Welcome to SLABC
Today’s Lecture
• Administration
• History
• Basic syntax
• The preprocessor
• Debug 101 – assert
• Style
2
Course Staff
Teacher + TA:
 C and first week of CPP - Elad Mezuman
 Last 3 weeks of CPP - Eva Kelman
Course exercises coordinator:
 Yonatan Vaizman
Don’t send emails to our personal mailboxes!
3
Time Schedule
3 weeks of C (1-17/8)
1 week of CPP (22+24/8)
1 week off from lectures (but with HW)
3 weeks of CPP (28/8-21/9)
Moed A – 27/9
Moed B – with moed A of the winter course
Lessons:
Mondays and Wednesday 9:00-12:00
Tirgul (2 groups):
Mondays and Wednesday 13:00-14:00 and 14:00-15:00
4
Communications
Web site: http://www.cs.huji.ac.il/~slabc
Please read the documents which are already on the
site.
Email:
Personal questions should be sent only to slabc@cs
You must specify your name, login and student ID in the
email.
Forums:
 News – must read
 Q & A – ask the staff about course material (not
exercises)
 Ex forums – ex related questions
 Exam forum – exam related questions
5
Course Grading
1. 4 programming exercises
2. Final exam
Final grade:
 50% exercises and 50% exam.
 You must have a pass grade both in the
exercises, and in the exam.
Shortage in computers - don’t wait for
the last minute.
6
Exercises Schedule
• First exercise (shorter than usual) due Sunday 7.8
(10:00 am)
• Other exercises will be due on Thursdays or Fridays
• We will talk about the exercises in the Tirguls
7
Late Submission
• Up until 24 hours (usually Sunday morning) – 10 points
reduction
• No need to request specifically (just attach the appropriate
document in the submission archive):
• Milluim
• Sickness (more than 1 day)
• More than 6 days abroad (will be granted only once per
student, boarding passes are needed)
• YOU are getting married
• Won’t be approved – no need to ask
• Moving
• Holidays / fasts
• My computer broke down (use backups!!!)
• We will answer requests regarding late submissions only for
very special occasions
8
Plagiarism policy
You may discuss your exercise with friends
You must not exchange any written material (or code)
between students
It is very easy to detect copying...
9
Course Objectives
1. Procedural programming language (C).
2. Pointers (C)
3. Structs (C)
4. Practice of programming:
 Style
 Testing & Debugging
 Efficiency & Portability
 Modularity
10
Books & Other resource
Books
1. “The C Programming Language” , 2nd Edition,
Brian W. Kernighan & Dennis M.Ritchie
2. “C in a Nutshell”, 1st edition, Peter Prinz & Tony
Crawford, O'reilly 2005.
3. “The Practice of Programming”, Brian W. Kernighan
& Rob Pike
4. “Programming Pearls” 2nd Edition, Jon Bentley
Web
1. Wikipedia the article C_(programming_language) to
begin with is a nice reading.
2. MSDN
3. http://www.cplusplus.com/ and
http://stackoverflow.com/
11
Working environments
Your exercises must run on the school machines
(Rottberg , Levi)
IDE (Integrated development environment): Emacs, eclipse
Working at home (always check it on the school
machines) • http://wiki.cs.huji.ac.il/wiki/Connecting_from_outside
 SSH to CS’s “river” server
 Install linux on your machine (don’t be afraid – windows
will remain) or on Virtual Machine (Virtual Box)
 Cygwin. (+Eclipse)
 Visual Studio (You can get professional edition from the
"aguda" for free)
 CodeBlocks – http://www.codeblocks.org
12
History
13
C
C++
Java
70’s – Development of UNIX.
(Richie+Kernigham – Bell labs)
80’s – Large efficient code.
(Stroustrup – Bell labs)
90’s – Language for the web.
(Sun Microsystems)
Simple to convert to
machine code.
VM
Fast and Efficient
Secure and Safe
Welcome to labC
Easy to avoid bugs
Easy to Debug
History – C:
• First "standard"
• Default int
K&R 1st
ed. ('78)
• Enums
• Return struct
• Fun. Prototypes
• void
ANSI C
('89)
• //
• VLA
• variadic macros
C99 ('99)
Current state, and this course:
Some major compilers comply to C99
(GCC) and some to ANSI C +some of
C99 (MSVC).
C – Design Decisions
“Bare bones” – the language leaves maximal flexibility to
the programmer
 Efficient code (operating systems)
 Full control on memory & CPU usage
High-level
 Type checking
 High-level constructs
Portable
 Standard language definition
 Standard library
15
C – Warning Signs
No run-time checks
 Array boundary overruns
 Illegal pointers
No memory management
 Programmer has to manage memory
16
C++ - OO extension of C
Classes & methods
 OO design of classes
Generic programming
 Template allow for code reuse
Stricter type system
Some run-time checks & memory control
17
First Program in C
// This is a comment
// This line defines standard I/O library
#include <stdio.h>
// main – name of the main part of the program
int main()
{ // {…} define a block
printf("Hello class!\n");
return 0;
}
18
Compiling & Running…
> gcc –Wall hello.c –o hello
> hello
Hello class!
>
19
Second Program
#include <stdio.h>
int main()
{
int i; // declares i as an integer
int j = 0; // declares j as an integer, and initializes it to 0
// for( initial ; test condition ; update step )
for( i = 0; i < 10; i++ )
{
j += i; // shorthand for j = j + i
printf("%d %d %d\n", i, j, (i*(i+1))/2);
}
return 0;
}
20
Running…
>
>
0
1
2
3
4
5
6
7
8
9
21
gcc –Wall loop.c –o loop
loop
0 0
1 1
3 3
6 6
10 10
15 15
21 21
28 28
36 36
45 45
Character Input/Output
#include <stdio.h>
int main()
{
int c;
while( (c = getchar()) != EOF )
{
putchar(c);
}
return 0;
}
22
Print header
#include <stdio.h>
#define HEADER 10
int main()
{
int n = 0;
int c;
while( ((c = getchar()) != EOF) && (n < HEADER) )
{
putchar(c);
if( c == '\n' )
n++;
}
return 0;
}
23
General Input/Output
#include <stdio.h>
int main()
{
int n;
float q;
double w;
printf("Please enter an int, a float and a double\n");
scanf("%d %f %lf",&n,&q,&w);
printf("ok, I got: n=%d, q=%f, w=%lf",n,q,w);
return 0;
}
24
Functions
C allows to define functions
Syntax:
Return type
Parameter
declaration
int power( int a, int b )
{
…
return 7;
}
25
Return
statement
Procedures
Functions that return void
void power( int a, int b )
{
…
return;
}
26
Return w/o value
(optional)
Example – printing powers
#include <stdio.h>
int main()
{
int power( int base, int n )
int i;
{
int i, p;
for( i = 0; i < 10; i++ )
{
p = 1;
printf("%d %d %d\n",
for( i = 0; i < n; i++ )
i,
{
power(2,i),
p = p * base;
}
27
power(-3,i) );
}
}
return p;
return 0;
}
Functions Declaration
void funcA()
{
...
}
void funcB()
{
funcA();
}
void funcC()
{
funcB();
funcA();
funcB();
}
28
void funcA()
{
...
}
void funcB()
{
funcC();
}
void funcC()
{
funcB();
}
“Rule 1”: A function
“knows” only
functions which were
declared above it.
Error:
funcC is not
known yet.
Functions Declaration
Amendment to “Rule 1” : Use forward declarations.
void funcC(int param);
// or: void funcC(int);
void funcA()
{
}
void funcB()
{
funcC(7);
}
void funcC(int param)
{
}
29
Primitive types
int main()
{
//Basic primitive types
printf("sizeof(char)
=
printf("sizeof(int)
=
printf("sizeof(float) =
printf("sizeof(double) =
%ld\n",sizeof(char));
%ld\n",sizeof(int));
%ld\n",sizeof(float));
%ld\n",sizeof(double));
//Other types:
printf("sizeof(void*) = %ld\n",sizeof(void*));
printf("sizeof(long double)= %ld\n",sizeof(long double));
return 0;
}
30
Boolean variables
int main()
{
int a = 5;
while(1)
{
if(!(a-3))
{
printf("** a=3 **\n");
break;
}
printf("a=%d\n",a--);
}
return 0;
}
31
The Preprocessor
• What it is
• The Common uses:
• #include
• #define
• #if/else/elif/endif
32
Compilation in C
hello.c
Preprocessor
tmpXQ.i
(C code)
Compiler
stdio.h
hello.o
(object
file)
33
Preprocessor
A single-pass program that:
1. Include header files
2. Expands macros
3. Control conditional compilation
4. Remove comments
Outputs – a code ready for the
compiler to work on.
34
Preprocessor
We can test what the preprocessor
does:
> gcc –E hello.c
will print the C code after running the
preprocessing
35
#include directive
#include "foo.h"
Include the file “foo.h”, from current directory
#include <stdio.h>
Include the file “stdio.h” from the standard
library directory (part of compiler installation)
36
Modules & Header files
square.h
int area
...
MyProg.c
#include "square.h"
int main()
{
area (2,3, 5,6);
}
37
(int x1,int y1, int x2, int y2);
Complex.c
square.c
#include "square.h"
#include <math.h>
// implementation
int area (int x1,int y1,int x2, int y2)
{
...
}
Header files
Header file contain
1. Definition of data types
2. Declarations of functions & constants
3. That are shared by multiple modules.
#include directive allows several
modules to share the same set of
definitions/declarations
38
#define directive
#define FOO 1
int x = FOO;
is equivalent to
int x = 1;
39
#define with arguments
#define SQUARE(x) x*x
b = SQUARE (a);
is the same as
b = a*a;
40
#define -- cautions
#define SQUARE (x) x*x
b = SQUARE (a+1);
c = SQUARE (a++);
Is it what we intended?
b = a+1*a+1;
//Actually: b = 2*a+1;
c = a++*a++;
//Actually: c = a*a; a+=2;
41
#define
#define directive should be used with
caution!
Alternative to macros:
• Constants
enum { FOO = 1 };
or
const int FOO = 1;
• Functions – inline functions (C++, later
on)
42
#if directive
Allows to have conditional compilation
#if defined(DEBUG)
// compiled only when DEBUG exists
printf("X = %d\n", X);
#endif
43
Debugging 101 - assert
assert.h
#include <assert.h>
// Sqrt(x) - compute square root of x
// Assumption: x
non-negative
double
Sqrt(double x )
{
assert( x >= 0 );
// aborts if x < 0
…
If the program violates the condition, then
assertion "x >= 0" failed: file "Sqrt.c", line 7 <exception>
The exception allows to catch the event in the debugger
45
assert.h
• Important coding practice
• Declare implicit assumptions
• Sanity checks in code
• Check for violations during
debugging/testing
Can we avoid overhead in production
code?
46
assert.h
// procedure that actually prints error message
void _assert(char* file, int line, char* test);
#ifdef NDEBUG
#define assert(e)
#else
#define assert(e)
((void)0)
\
((e) ? (void)0 :
\
__assert(__FILE__, __LINE__, #e))
#endif
47
General purpose debug function
// file: my_debug.h
// defines a general purpose debug printing function
// usage: same as printf,
// to disable the printing define the macro NDEBUG
#ifdef NDEBUG
#define printDEBUG(format, ...) (void (0))
#else
#define printDEBUG(format, ...)
printf(format, __VA_ARGS__)
#endif
48
\
Program Style
1. Readability
2. Common Sense
3. Clarity
4. Right focus
49
What’s in a name
Example
#define ONE 1
#define TEN 10
#define TWENTY 20
More reasonable
#define INPUT_MODE 1
#define INPUT_BUFSIZE 10
#define OUTPUT_BUFSIZE 20
50
What’s in a name
Use descriptive names for global variables
int npending = 0; // current length of input queue
Naming conventions are fixed in our course
 numPending
 num_pending
 NumberOfPendingEvents
…
51
What’s in a name
Compare
for( the_element_index = 0;
the_element_index < number_of_elements;
the_element_index++ )
element_array[the_element_index] = the_element_index;
and
for( i = 0; i < nelems; i++ )
elem[i] = i;
Use short names for locals
52
What’s in a name
Consider:
int num_of_items_in_q;
int front_of_the_queue;
int queue_capacity;
…
The word “queue” appears in 3 different ways
Be Consistent
 Follow naming guidelines used by your peers
53
What’s in a name
Use active name for functions
now = getDate()
Compare
if( checkDigit(c) ) …
to
if( isDigit(c) ) …
Accurate active names makes bugs apparent
54
Indentation
Use indentation to show structure
Compare
for(n++; n <100; field[n++] = 0);
c = 0; return ‘\n’;
To
for( n++; n <100; n++)
{
field[n] = 0;
}
c = 0;
return ‘\n’;
55
Expressions
Use parentheses to resolve ambiguity
Compare
leap_year = y % 4 == 0 && y %100 != 0
|| y % 400 == 0;
to
leap_year = ((y % 4 == 0) && (y %100 != 0))
|| (y % 400 == 0);
56
Statements
Use braces to resolve ambiguity
Compare
if( i < 100 )
x = i;
i++;
To
if( i < 100 )
{
x = i;
}
i++;
57
Idioms
Do not try to make code “interesting”
i = 0;
while( i <= n-1 )
array[i++] = 1;
for( i = 0; i < n; )
array[i++] = 1;
for( i = n; --i >= 0; )
array[i] = 1;
for( i = 0; i < n; i++ )
array[i] = 1;
58
This is the common “idiom”
that any programmer will
recognize
Idioms
Use “else if” for multiway decisions
if ( cond1 )
statement1
else if ( cond2 )
statement2
…
else if ( condn )
statementn
else
default-statement
59
Idioms
if( x > 0 )
if( y > 0 )
if( x+y < 100 )
{
...
}
else
printf(Too large!\n" );
else
printf("y too small!\n");
else
printf("x too small!\n");
60
if( x <= 0 )
printf("x too small!\n");
else if( y <= 0 )
printf("y too small!\n");
else if( x+y >= 100 )
printf("Sum too large!\n" );
else
{
...
}
Comments
Don’t write the obvious
// return SUCCESS
return SUCCESS;
// Initialize total to number_received
total = number_received;
Test:
Does comment add something that is not evident from
the code?
61
Comments
#include <math.h>
// random: return a random integer in [0..r]
int random( int r )
{
return (int)(r * (rand() / (RAND_MAX + 1.0)));
}
Note: “//” Comments are Not Strict ANSI C, but
supported by all modern compilers, and clearer in many
cases
62
Comments
A more elaborate function comment:
//
// GammaGreaterThanOne( Alpha )
//
// Generate a gamma random variable when alpha > 1.
//
// Assumption: Alpha > 1
//
// Reference: Ripley, Stochastic Simulation, p.90
// Chang and Feast, Appl.Stat. (28) p.290
//
double GammaGreaterThanOne( double Alpha )
{
63
…
Comments
Don’t comment bad code – rewrite it!
…
// If result = 0 a match was found so return
// true; otherwise return false;
return !result;
Instead
…
return matchfound;
64
Style recap
 Descriptive names
 Clarity in expressions
 Straightforward flow
 Readability of code & comments
 Consistent conventions & idioms
65
Why Bother?
Good style:
 Easy to understand code
 Smaller & polished
 Makes errors apparent
Sloppy code bad code
 Hard to read
 Broken flow
 Harder to find errors & correct them
66
Download