You are on page 1of 61

1

PROGRAMMING IN C
C: History
2

 Developed in the 1970s – in conjunction with


development of UNIX operating system
 When writing an OS kernel, efficiency is crucial
This requires low-level access to the underlying hardware:
 e.g. programmer can leverage knowledge of how data is laid out
in memory, to enable faster data access
 UNIX originally written in low-level assembly language –
but there were problems:
 No structured programming (e.g. encapsulating routines as
“functions”, “methods”, etc.) – code hard to maintain
 Code worked only for particular hardware – not portable
C: Characteristics
3

 C takes a middle path between low-level


assembly language…
 Direct access to memory layout through pointer
manipulation
 Concise syntax, small set of keywords
 … and a high-level programming language like
Java:
 Block structure
 Some encapsulation of code, via functions
 Type checking (pretty weak)
C: Dangers
4

 C is not object oriented!


 Can’t “hide” data as “private” or “protected” fields
 You can follow standards to write C code that looks
object-oriented, but you have to be disciplined – will the
other people working on your code also be disciplined?
 C has portability issues
 Low-level “tricks” may make your C code run well on one
platform – but the tricks might not work elsewhere
 The compiler and runtime system will rarely stop
your C program from doing stupid/bad things
 Compile-time type checking is weak
 No run-time checks for array bounds errors, etc. like in
Java
Separate compilation
5

 A C program consists of source code in one or more files


 Each source file is run through the preprocessor and compiler,
resulting in a file containing object code
 Object files are tied together by the linker to form a single executable
program
Source code Preprocessor/ Object code
file1.c Compiler file1.o

Source code Preprocessor/ Object code


file2.c Compiler file2.o

Libraries
Linker

Executable code
a.out

CS 3090: Safety Critical Programming in C


Separate compilation
6

 Advantage: Quicker compilation


 When modifying a program, a programmer typically
edits only a few source code files at a time.
 With separate compilation, only the files that have
been edited since the last compilation need to be
recompiled when re-building the program.
 For very large programs, this can save a lot of time.
The preprocessor
7

 The preprocessor takes your source code and – following certain


directives that you give it – tweaks it in various ways before
compilation.
 A directive is given as a line of source code starting with the #
symbol
 The preprocessor works in a very crude, “word-processor” way,
simply cutting and pasting –
it doesn’t really know anything about C!
Your Enhanced and
source obfuscated Object
code source code code

Preprocessor Compiler
A first program: Text rearranger
8

 Input
 First line: pairs of nonnegative integers, separated by
whitespace, then terminated by a negative integer
x1 y1 x2 y2 … xn yn -1
 Each subsequent line: a string of characters
 Output
 For each string S, output substrings of S:
 First, the substring starting at location x1 and ending at y1;
 Next, the substring starting at location x2 and ending at y2;
 …
 Finally, the substring starting at location xn and ending at xn.
Use of comments
9 /*
** This program reads input lines from the standard input and prints
** each input line, followed by just some portions of the lines, to
** the standard output.
**
** The first input is a list of column numbers, which ends with a
** negative number. The column numbers are paired and specify
** ranges of columns from the input line that are to be printed.
** For example, 0 3 10 12 -1 indicates that only columns 0 through 3
** and columns 10 through 12 will be printed.
*/

 Only /* … */ for comments – no // like Java or C++


Comments on comments
10
 Can’t nest comments within comments
 /* is matched with the very next */ that comes along

 Don’t use /* … */ to comment out code – it won’t work if the commented-


out code contains comments

/* Comment out the following code


int f(int x) { Only this will be
return x+42; /* return the result */ commented out

}
This will not!
*/
 Anyway, commenting out code is confusing, and dangerous (easy to forget
about) – avoid it
A Simple C Program
 int main()
 C programs contain one or more functions, exactly
one of which must be main
 Parenthesis used to indicate a function
 int means that main "returns" an integer value
 Braces ({ and }) indicate a block
 The bodies of all functions must be contained in braces
2.2 A Simple C Program:
Printing a Line of Text
 Return 0;
 A way to exit a function
 Return 0, in this case, means that the program
terminated normally
Preprocessor directives
13

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

 The #include directives “paste” the contents of the files stdio.h, stdlib.h and
string.h into your source code, at the very place where the directives appear.
 These files contain information about some library functions used in the
program:
 stdio stands for “standard I/O”, stdlib stands for “standard library”, and

string.h includes useful string manipulation functions.


 Want to see the files? Look in /usr/include
Preprocessor directives
14

#define MAX_COLS 20
#define MAX_INPUT 1000

 The #define directives perform


“global replacements”:
 every instance of MAX_COLS is replaced with 20, and
every instance of MAX_INPUT is replaced with 1000.

CS 3090: Safety Critical Programming in C


Function prototypes
15

int read_column_numbers( int columns[], int max );


void rearrange( char *output, char const *input,
int n_columns, int const columns[] );

 These look like function definitions – they have the name and all the type
information – but each ends abruptly with a semicolon. Where’s the body
of the function – what does it actually do?
 (Note that each function does have a real definition, later in the program.)

CS 3090: Safety Critical Programming in C


Function prototypes
16

 Q: Why are these needed, if the functions are defined later in the program
anyway?
 A: C programs are typically arranged in “top-down” order, so functions are
used (called) before they’re defined.
 (Note that the function main() includes a call to
read_column_numbers().)
 When the compiler sees a call to read_column_numbers() , it must check
whether the call is valid (the right number and types of parameters, and
the right return type).
 But it hasn’t seen the definition of read_column_numbers() yet!

 The prototype gives the compiler advance information about the function
that’s being called.
 Of course, the prototype and the later function definition must match in
terms of type information.
The main() function
17

 main() is always the first function called in a program execution.

int
main( void )
{…

 void indicates that the function takes no arguments


 int indicates that the function returns an integer value
 Q: Integer value? Isn’t the program just printing out some stuff and then exiting?
What’s there to return?
 A: Through returning particular values, the program can indicate whether it
terminated “nicely” or badly; the operating system can react accordingly.

CS 3090: Safety Critical Programming in C


The printf() function
18

printf( "Original input : %s\n", input );


 printf() is a library function declared in <stdio.h>
 Syntax: printf( FormatString, Expr, Expr...)
 FormatString: String of text to print
 Exprs: Values to print
 FormatString has placeholders to show where to put the values (note:
#placeholders should match #Exprs)
 Placeholders: %s (print as string), %c (print as char),
%d (print as integer),
Make sure you pick
%f (print as floating-point)
the right one!
 \n indicates a newline character

Text line printed only


when \n encountered
Don’t forget \n when
printing “final results”
return vs. exit
19
 Let’s look at the return statement in main():

return EXIT_SUCCESS;

 EXIT_SUCCESS is a constant defined in stdlib ; returning this value signifies successful


termination.
 Contrast this with the exit statement in the function read_column_numbers():

puts( “Last column number is not paired.” );


exit( EXIT_FAILURE );

 EXIT_FAILURE is another constant, signifying that something bad happened requiring


termination.
 exit differs from return in that execution terminates immediately – control is not passed back to
the calling function main().
C DATA TYPES
What do program instructions look like?

 A simple program has at least these three main


parts
 variable declaration
 variable initialization
 main body
Variables in Programming
 Represent storage units in a program
 Used to store/retrieve data over life of program
 Type of variable determines what can be placed in
the storage unit
 Assignment – process of placing a particular value
in a variable
 Variables must be declared before they are
assigned
 The value of a variable can change; A constant
always has the same value
Naming variables
 When a variable is declared it is given a name
 Good programming practices
 Choose a name that reflects the role of the variable in a
program, e.g.
 Good: customer_name, ss_number;
 Bad : cn, ss;
 Don’t be afraid to have long names if it aids in readability
 Restrictions
 Name must begin with a letter; otherwise, can contain
digits or any other characters. C is CASE SENSITIVE! Use
31 or fewer characters to aid in portability
Variable Declaration
 All variables must be declared in a C program
before the first executable statement! Examples:
main(){
int a, b, c;
float d;
/* Do something here */
}
C Variable Names
 Variable names in C may only consist of letters,
digits, and underscores and may not begin with
a digit
 Variable names in C are case sensitive
 ANSI standard requires only 31 or fewer
characters. Enhances portability to follow this
rule
 Should be very descriptive
Variable assignment
 After variables are declared, they must (should)
be given values. This is called assignment and it
is done with the ‘=‘ operator. Examples:
float a, b;
int c;
b = 2.12;
c = 200;
Basic C variable types
 There are four basic data types in C:
 char
 A single byte capable of holding one character in the
local character set.
 int
 An integer of unspecified size
 float
 Single-precision floating point
 double
 Double-precision floating point
char variable type
 Represents a single byte (8 bits) of storage
 Can be signed or unsigned
 Internally char is just a number
 Numerical value is associated with character via a
character set.
 ASCII character set used in ANSI C
 Question: what is the difference between:
 printf(“%c”, someChar);
 printf(“%d”, someChar);
int variable type
 Represents a signed integer of typically 4 or 8
bytes (32 or 64 bits)
 Precise size is machine-dependent
 Question: What are the maximum and minimum
sizes of the following:
 32-bit unsigned int
 32-bit signed int
 64-bit signed/unsigned int
 What happens if these limits are exceeded?
float and double variable types
 Represent typically 32 and/or 64 bit real
numbers
 How these are represented internally and their
precise sizes depend on the architecture. We
won’t obsess over this now.
 Question: How large can a 64-bit float be?
 Question: How many digits of precision does a
64-bit float have?
Additional variable types
 Note that other types can be constructed using
the modifiers:
 short, long, signed, unsigned
 The precise sizes of these types is machine-
specific
 We will not worry about them for the time being
 To find out the meaning of short int, etc. on a
given system, use <limits.h>
Declaring variables
 All variables must always be declared before the
first executable instruction in a C program
 Variable declarations are always:
 var_type var_name;
 int age;
 float annual_salary;
 double weight, height; /* multiple vars ok */
 In most cases, variables have no meaningful value
at this stage. Memory is set aside for them, but
they are not meaningful until assigned.
Assigning values to Variables
 Either when they are declared, or at any
subsequent time, variables are assigned values
using the “=“ operator.
 Examples
int age = 52; //joint declaration/assignment
double salary;
salary = 150000.23;
age = 53; //value may change at any time
Assignment, cont.
 Be careful to assign proper type – contract
between declaration and assignments must be
honored
 int x=2.13 /* what is the value of x? */
 double x = 3; /* is this ok? */
 char c = 300; /* 300 > 1 byte; what happens? */
Structure of a C program
 So far our C programs are as follows:
/* description of program */
#include <stdio.h>
/* any other includes go here */
int main(){
/* program body */
return 0;
}

 Let’s learn more about the structure of “program body”


Program Body - declarations
 Always begins with all variable declarations. Some
examples:
int a, b, c; /* declare 3 ints named a,b,c */
int d, e; /* similar to above in two steps */
int f;
int g = 1, h, k=3;
double pi = 3.1415926;
 Reading note: K&R mentions that integers can be

assigned in octal and hexadecimal as well. We will


discuss this later. Certainly, not important for most
applications.
Statements
 Note: all statements end with a semicolon!
 Statements can (with a few exceptions) be broken
across lines or ganged on a single line
 Commas separate multiple declarations
 Blank lines have no effect
 Extra spaces between tokens has no effect.
 Comments are ignored by the compiler
Program Body – Executable
Statements
 Executable statements always follow variable
declarations/initializations
 Executable statements include any valid C code
that is not a declaration, ie valid C code to do
things like:
 “multiply the value of a by 10 and store the result in b”
 “add 1 to the value of j and test whether it is greater than
the value of k”
 “store 5.2 in the variable x” (ie assignment)
 “print the value of x,y, and z, each on a separate line”
The printf Executable Statement
 The only executable statements we’ve seen to
this point are
 Assignments
 The printf and scanf functions
 Assignment expressions with simple operators (+, -)
 Very hard to write any program without being
able to print output. Must look at printf in more
detail to start writing useful code.
printf(), cont.
 Sends output to standard out, which for now we
can think of as the terminal screen.
 General form
printf(format descriptor, var1, var2, …);
 format descriptor is composed of
 Ordinary characters
 copied directly to output
 Conversion specification
 Causes conversion and printing of next argument to printf
 Each conversion specification begins with %
Printf() examples
 Easiest to start with some examples
 printf(“%s\n”, “hello world”);
 Translated: “print hello world as a string followed by a newline
character”
 printf(“%d\t%d\n”, j, k);
 Translated: “print the value of the variable j as an integer
followed by a tab followed by the value of the variable k as an
integer followed by a new line.”
 printf(“%f : %f : %f\n”, x, y, z);
 English: “print the value of the floating point variable x, followed
by a space, then a colon, then a space, etc.
More on format statements
 The format specifier in its simplest form is one of:
 %s
 sequence of characters known as a String
 Not a fundamental datatype in C (really an array of char)
 %d
 Decimal integer (ie base ten)
 %f
 Floating point
 Note that there are many other options. These are
the most common, though, and are more than
enough to get started.
Invisible characters
 Some special characters are not visible directly
in the output stream. These all begin with an
escape character (ie \);
 \n newline
 \t horizontal tab
 \a alert bell
 \v vertical tab
 See K&R p.38 for more details
Recap
44

 C is a high-level language.

 Writing a C code. {editors like gedit, vi}

 Compiling a C code. {gcc –c test.c –o test}

 Executing the object code. {./test}

C Course, Programming club, Fall 2008


Some more basics
45

 Keywords
 char, static, if , while, return ..................... Total= about 32

 Data Types
 int , char, float ...………..….. Some more later

 Arithmetic Operators
 + (Plus), - (Minus), * (Multiplication), /(Division)
……….………. Some more later

C Course, Programming club, Fall 2008


My first C program!
46

#include <stdio.h>
// program prints hello world
int main() {
printf ("Hello world!");
return 0;
}

Output: Hello world!

C Course, Programming club, Fall 2008


Example 1
47

#include <stdio.h>
// program prints a number of type int
int main() {
int number = 4;
printf (“Number is %d”, number);
return 0;
}

Output: Number is 4

C Course, Programming club, Fall


2008
Example 2
48

#include <stdio.h>
// program reads and prints the same thing
int main() {
int number ;
printf (“ Enter a Number: ”);
scanf (“%d”, &number);
printf (“Number is %d\n”, number);
return 0;
}

Output : Enter a number: 4


Number is 4
C Course, Programming club, Fall
2008
more and more
49

#include <stdio.h>

int main() {
/* this program adds
two numbers */
int a = 4; //first number
int b = 5; //second number
int answer = 0; //result
answer = a + b;
}

C Course, Programming club, Fall 2008


Note
50

Errors
Compilation
Compiler generally gives the line number at
which the error is present.
Run time
C programs are sequential making the debugging
easier.

C Course, Programming club, Fall 2008


Some more Data Types
51

 Primary : int, float, char


 int (signed/unsigned)(2,4Bytes): used to store integers.
 char (signed/unsigned)(1Byte): used to store
characters
 float, double(4,8Bytes): used to store a decimal number.

 User Defined:
 typedef: used to rename a data type
 typedef int integer; can use integer to declare an int.
 enum, struct, union
C Course, Programming club, Fall
2008
Some more Arithmetic Operators
52

 Prefix Increment : ++a


 example:
 int a=5;
 b=++a; // value of b=6; a=6;

 Postfix Increment: a++


 example
 int a=5;
 b=a++; //value of b=5; a=6;

C Course, Programming club, Fall 2008


Contd…
53

 Modulus (remainder): %
 example:
 12%5 = 2;

 Assignment by addition: +=
 example:
 int a=4;
 a+=1; //(means a=a+1) value of a becomes 5

Can use -, /, *, % also

C Course, Programming club, Fall 2008


Contd…
54

 Comparision Operators: <, > , <=, >= , !=, ==, !,


&&, || .
 example:
 int a=4, b=5;
 a<b returns a true(non zero number) value.

 Bitwise Operators: <<, >>, ~, &, | ,^ .


 example
 int a=8;
 a= a>>1; // value of a becomes 4

C Course, Programming club, Fall 2008


Operator Precedence
55

 Meaning of a + b * c ?
is it a+(b*c) or (a+b)*c ?
 All operators have precedence over each other
 *, / have more precedence over +, - .
 If both *, / are used, associativity comes into
picture. (more on this later)
 example :
 5+4*3 = 5+12= 17.

C Course, Programming club, Fall 2008


Precedence Table
56

Highest on top
++ -- (Postfix)
++ -- (Prefix)
* / %
+ -
<< >>
< >
&
|
&&
||

C Course, Programming club, Fall 2008


Input / Output
57

 printf (); //used to print to console(screen)


 scanf (); //used to take an input from console(user).
 example: printf(“%c”, ’a’); scanf(“%d”, &a);
 More format specifiers
%c     The character format specifier.
%d     The integer format specifier.
%i     The integer format specifier (same as %d).
%f     The floating-point format specifier.
%o     The unsigned octal format specifier.
%s     The string format specifier.
%u     The unsigned integer format specifier.
%x     The unsigned hexadecimal format specifier.
%%     Outputs a percent sign.
C Course, Programming club, Fall 2008
Some more geek stuff
58

 & in scanf.
 It is used to access the address of the variable used.
 example:
 scanf(%d,&a);
 we are reading into the address of a.

 Data Hierarchy.
 example:
 int value can be assigned to float not vice-versa.
 Type casting.

C Course, Programming club, Fall 2008


Home Work
59

 Meaning of
 Syntax
 Semantics of a programming language
 Find the Output:
 value=value++ + value++;
 Value=++value + ++value;
 value=value++ + ++value;

C Course, Programming club, Fall 2008


End of Today’s Lecture
60

Doubts && Queries?

C Course, Programming club, Fall 2008


61

THANK YOU

C Course, Programming club, Fall 2008

You might also like