lecture 2: starting out c hello, world!. our first c program since c programs are just raw text...

33
Lecture 2: Starting Out C Hello, world!

Upload: walter-lambert

Post on 20-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Lecture 2: Starting Out C

Hello, world!

Page 2: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Our First C Program

• Since C programs are just raw text without any decorations, you can use any text editor you like to write the C source code, and compile it into an executable with any C compiler of your choice

• In practice, most programming is done using some integrated development environment (IDE) that hides the compiler and various other programming tools under a consistent unified interface

• In this course, the free Quincy IDE is quite sufficient• Eclipse is a popular IDE for many languages• Allows you to edit, build, run and debug your programs• Create the first project, write the first program...

Page 3: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Hello, world!

/* Our first C program consists of one preprocessor directive, one function (main) that contains two statements to be executed when the program is run. By convention, when learning a new language or environment, the first program to try out is the "hello world", if only to check that the programming environment has been set up properly. */

#include <stdio.h>

int main() {    printf("Hello, world!\n");    return 0;}

Page 4: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Functions

• C is a very low level programming language in that the only higher-level abstraction mechanism that it supports is the procedural abstraction with functions

• Your program consists of one or more functions, one of which must be called main. This is a special function automatically invoked when your program starts.

• Each function consists of a series of statements. Each statement is a specific instruction for the computer to do something. The statements are executed in order when the function is invoked.

• There are not very many individual statements in C, but as building blocks put together, they can in principle express any algorithmically possible computation.

Page 5: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Behavioural Abstraction

• In theory, you could write your entire program as one main function containing only bare C statements. In practice, it is better to split the program into functions.

• Every time you define a function, you are effectively adding a new higher-level statement to your personal C language to be used in other functions.

• These functions can then be used to create even higher-level functions, and so on, this way building up an arbitrarily complex program out of simple parts.

• To avoid reinventing the wheel, useful and commonly needed functions are collected into libraries. For example, the system library stdio.h defines the printf function that we use as a statement inside the main function.

Page 6: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Braces and Indentation

• When writing our programs, we need some way to unambiguously indicate the static structure of the program, especially what is nested inside what.

• In C and related languages, curly braces { } are used to indicate where something begins and ends. Anything between these braces is nested inside them.

• The compiler doesn't care about whitespace, but we humans do a lot. Indent your program properly so that each statement is in a single line, and each open brace increases indentation by one tab, whereas each closing braces decreases indentation by one tab.

• Braces always come in pairs, and they can be nested arbitrarily deep.

Page 7: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Strings and Escape Sequences

• Strings, pieces of text, are represented in C inside double quote characters. When the compiler sees a double quote mark, it reads everything until the next double quote mark as raw characters, without trying to interpret it as C code.

• The statement printf("Hello, world!\n"); invokes the function printf and gives it a string as an argument.

• The function printf has been written so that it outputs its argument on the standard output of the program.

• Escape sequences are a way to include special characters inside a C string where this is not otherwise syntactically feasible. For example, \n encodes a newline character. (Google the rest.)

• Even though C is otherwise indifferent to whitespace, whitespace matters inside strings and output.

Page 8: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Additional Syntax Rules of C

• You can add documentary comments in your code by encoding them between the separators /* and */

• Comments can never affect the behaviour of the program, and are meant to explain for human readers the thought process of the programmer who wrote the code

• Comments document why, the code already says what• Normally, you write one statement per line inside a function• However, C is designed to be insensitive to whitespace, so

line breaks cannot be used to disambiguate the syntax• Every statement in C must end with semicolon to make it

clear where the statement ends and the next one begins• Note that #include is not a statement, but a preprocessor

directive applied before the actual compilation

Page 9: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Local Variables

• Functions need to keep track of various pieces of data that have been given to them, and also keep track of various intermediate results of long computations.

• The first example used no data and therefore made no decisions based on it, and behaves the exact same way every time it is run

• To use a piece of data inside a function, you must declare it as a local variable at the beginning of the function.

• You can define as many local variables as you want, but they all vanish once the function execution terminates.

• To define a local variable, simply give its type (int for an integer, double for a decimal number) followed by an identifier, a name that you later use to talk about it

Page 10: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Example: Some Basic Arithmetic

#include <stdio.h>

int main() {    /* First, define some local variables. */    int feet = 100;    int inches_in_feet = 12;    int inches;    /* Now we can use them in our statements. */    inches = feet * inches_in_feet;    printf("There are %d inches in %d feet.\n", inches, feet);    return 0;    /* Our local variables cease to exist here. */ }

Page 11: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Placeholders in printf

• In the Hello world, we used printf to output a single string• In general, printf can be given an arbitrary list of

arguments, individual arguments separated with commas• The first argument must always be a format string, but the

rest can be anything you want• When the function printf outputs your format string, it

replaces each placeholder (items starting with %) with the corresponding argument value in the argument list

• The placeholders must define the type of data that you want to output, so that printf knows to interpret its raw bytes and convert them to characters correctly

• Placeholders are %d for integers, %lf for doubles• (d is for "decimal" in the sense "base 10")

Page 12: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Interlude: Dialects of C

• C has come some way from its 1970's beginnings• Different compiler vendors implement things differently• First standard 1989 ANSI C• Every compliant C installation is guaranteed to have certain

standard libraries and there certain functions• Language features are guaranteed to behave certain way• However, many features are still left machine- and

implementation-dependent, for example, the exact size of types such as int and double

• Later standards C99 and now C11 give programmer more freedom and power

• You can now declare variables close to place of use

Page 13: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Assignment Statement

• The assignment is used to give variables their values, copy data from one variable to another, and perform mathematical calculations on the data along the way.

• The statement is of the form lhs = rhs; where the left hand side is a single variable, and the right hand side is an arbitrary expression (some mathematical formula that evaluates to some value)

• The assignment evaluates the rhs expression, and stores its current value to the lhs variable. The previous value of the lhs variable disappears forever.

• It is easy to hallucinate all sorts of wonderful magic things happening in the assignment statement. However, this is the only thing that it does; no more and no less.

Page 14: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Assignment Exercise

#include <stdio.h>/* Keep your eye solidly on the ball with this one. */int main() {     int a = 2; int b = 3;    printf("a is now %d, b is now %d\n", a, b); /* #1 */    a = b + 3;    printf("a is now %d, b is now %d\n", a, b); /* #2 */    b = 4; /* note how a does not change! */    printf("a is now %d, b is now %d\n", a, b); /* #3 */    a = a + 4; /* Sure seems paradoxical... */    printf("a is now %d, b is now %d\n", a, b); /* #4 */    return 0;}

Page 15: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Interlude: Imperative Programming

• In the taxonomy of high-level programming languages, C belongs to the family of imperative languages

• Imperative languages express the computation as series of statements that modify the current state of the data

• Each statement modifies some variable or memory location, and determines which program statement is executed next

• Program cannot modify itself while it runs, though• As a programmer who wants to solve a given problem, you

need to devise an entire series of statements whose execution leads from the input to the desired results

• Non-imperative languages allow you to talk about inputs and results, and let the computer fill in execution steps

Page 16: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Destructive Assignment

• In imperative programming, only the present moment exists, and the past history is gone forever

• Unlike in mathematics floating there in the harmonious Platonic world outside time and space, it is not contradictory for x to first equal 5, and then later equal 7

• C is not a spreadsheet: every variable contains only its current value, but no history of past values or information of where its current value came from

• When you assign a = b + c; you are only storing the current value of the expression b + c into variable a, not the expression b + c where that value came from

• If either variable b or c later changes, the variable a does not automatically change to reflect this

Page 17: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Arithmetic Shorthand Operators

• In spirit of terseness, C offers many shorthand forms of common arithmetic operations

• For example, a common kind of assignment a = a + b to increment the value of a can be shortened to a += b, and the same for other arithmetic operators -, *, /

• As we will see, incrementing and decrementing by 1 is extremely common, so there is a special insider shorthand

• To increment a by 1, use a++ or ++a• To decrement a by 1, use a-- or --a• But not a = a++;• For modern compilers that we would take seriously today,

none of these runs any faster than the full explicit form

Page 18: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Pitfalls of Shorthand Forms

• When a variable is incremented as a single statement, it doesn't matter whether you use ++ from left or from right

• However, when this increment operation is part of a larger expression, this suddenly matters a great deal

• Incrementing from left first increments the variable and then uses it, whereas incrementing from right first uses the variable and then increments it

• Contrast the two assignments b = a++; and b = ++a;• Also, if some variable is incremented or decremented, that

same variable should not occur anywhere else in the entire statement

• How would the statement a = ++a + a++ + a-- + --a; work? We can't say, and in fact its behaviour is undefined.

Page 19: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Hard Rules for Identifiers

• In your program, you must give a name for each function and variable so that it is always unambiguous for the compiler what you are talking about. This name must be some legal identifier.

• In C, an identifier may consist only of letters (both small and capital), digits and underscores.

• Furthermore, an identifier may not begin with a digit• An identifier may not be the same as any reserved word in

C, although it may contain one as a part. For example, int cannot be used as identifier, but intel can.

• If an identifier consists of several words, the convention is to separate_them_with_underscores for readability.

Page 20: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Soft Rules for Identifiers

• An identifier may begin with an underscore, but you should avoid such names in your programs, since these names may accidentally conflict with identifiers defined in various C standard libraries.

• You should also avoid using names of functions in standard library as your identifiers, even though legal.

• Naming an identifier in ALL_CAPITALS is a convention to inform the human reader that the identifier is not a variable or a function, but a preprocessor constant.

• If you really must, define a preprocessor constant with the directive #define. Note that this is not a statement nor an assignment, but simple search-and-replace done by the preprocessor, and surprisingly error-prone.

Page 21: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Preprocessor Macros

• Before your C program is compiled, it is run through a simple text processing utility called preprocessor

• Performs simple macro substitutions on your program based on preprocessor directives

• For example, #include simply inserts the contents of the given file to that position in the file

• Directive #define lets you define simple find-and-replace substitutions of text

• For example, #define PI 3.1415926• Note the lack of semicolon, because if you put a semicolon

after the substituted value, that semicolon would also be pasted to wherever PI appears, causing a syntax error

Page 22: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Macro Pitfalls

• The C macro substitution mechanism can handle simple substitution of macro parameters, but it is essential to remember that this really is just dumb text substitution, no different from using replace-all in text editor

• For example, #define SQ(a) a*a• This fails to correctly expand the formula SQ(x+y), which

becomes x+y*x+y, not quite what was intended• Note that adding spaces would not help• Try again: #define SQ(a) ((a)*(a))• This will also fail if a is something that has side effects

when it is evaluated, since a will be evaluated twice• Prefer functions and named constants over macros

Page 23: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Floating Point Placeholders

• Especially the floating point numbers of type double should always be output rounded to some reasonable number of decimal places. The %lf placeholder can be given additional control information to achieve this.

• To control the number of decimal places, put a dot and this desired number between % and lf.

• printf("%.2lf", 123.45678); /* 123.46 */• You can additionally control the total width of the output to,

for example, make columns of numbers line up nicely • printf("%7.2lf", 12.3456); /* __12.34 */• You can similarly control the integer output.• printf("%7d", 123); /* ____123 */

Page 24: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

User Input Example

#include <stdio.h>

int main() {    int inches_in_feet = 12;    int feet, inches; /* Uninitialized values */    /* Ask the user for how many feet there are. */    printf("Enter the length in feet: ");    scanf("%d", &feet); /* Read the answer */    inches = feet * inches_in_feet;    printf("There are %d inches in %d feet.\n", inches, feet);    return 0;    /* All our local variables cease to exist here. */ }

Page 25: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

scanf

• The function scanf is defined in the standard library stdio.h to read input from the outside world and the human user.

• To use this function, call it with with the format string that contains the placeholders for the type of data that you are expecting, followed by the variable(s) where you want to stored the values that were read

• However, a special syntax is needed to pass these variables as arguments, since you really want to pass their memory addresses, not their values. Otherwise, the function scanf could not know where to write its results.

• In C, prefixing a variable name with an ampersand gives the memory address of that variable.

Page 26: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Look at Those Bytes

#include <stdio.h>

int main() {    double x = 123.4567;    printf("The value of x as double is %.3lf.\n", x);    printf("It is stored in %d bytes.\n", sizeof(x));    printf("It is stored in the memory address %p.\n", &x);    printf("Viewed as an int, its value is %d.\n", x);    printf("Cast into an int, its value is %d.\n", (int) x);    printf("Its memory address viewed as int is %d.\n", &x);    return 0;}

Page 27: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Standard I/O

• The library stdio.h is aptly named, since the functions defined in it access the standard input and standard output that your program reads and writes its data

• When a program is started, both of these are by default connected to the console, but it doesn't have to be thus

• For example, a program might read its inputs from the file data.txt, in which case it would be launched from the command line with the command myprog < data.txt

• The program itself doesn't change, only its standard input is now coming from a different place, and now typing stuff on console does nothing

• Conversely, the program might write its output into the file results.txt, so it would be launched myprog > results.txt

Page 28: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Pipes

• The Unix philosophy states that every program should do one and only one thing and do it well, and programs can be chained with pipes so that the output of each program in the chain becomes the input for the next

• For example, the program ls only lists the contents of the directory, but doesn't do any input paging, which is done by another program called more. (Or, less.)

• To run three programs foo, bar and baz chained this way, you'd issue the command foo | bar | baz > results.txt

• In this example, foo reads its input (if any) from its standard input (here console), and baz writes its output to its standard output (here the file results.txt) 

Page 29: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Interlude: Placeholder Names

• The previous example used three canonical placeholder names foo, bar and baz commonly seen in all material written by programmers for programmers (also qux)

• When the exact identity of something we need to talk about in an example or a problem is irrelevant, these canonical placeholders inform the human reader that this exact identity is irrelevant for the point that we are making

• Seen in many other walks of life: for example, an Econ textbook problem might start "A factory can produce widgets for $2 per widget, and..."

• For problems involving people, canonical placeholder names have historically been "Moe and Joe", "Alice, Bob, Carol, Dave", etc.

Page 30: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Explicit File Reading Example

#include "stdio.h"

int main() {    FILE* f;    int x;

    f = fopen("data.txt", "r");    fscanf(f, "%d", &x);    printf("Read the number %d from the file.\n", x);    fclose(f);    printf("File closed, terminating.\n");    return 0;}

Page 31: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

fscanf

• fscanf behaves otherwise exactly like scanf, but instead of reading from the standard input, it always reads from the file given to it as its first argument, the remaining arguments being same as in the function scanf

• Redirection and pipes do not affect fscanf in any way• To open a file for reading, you must first declare a FILE*

variable (the asterisk means a pointer, not multiplication), and then use the function fopen to open it

• Once opened for either reading ("r"), writing ("w") or appending ("a"), that file is in your exclusive use, and cannot be accessed by other processes until you give it up with the function fclose

• fprintf works like fscanf, with the file as first argument

Page 32: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

Error Handling in (f)scanf

• scanf and fscanf assign the data they read into addresses that you pass to them as arguments

• Compiler type checking is not in effect for placeholders, so if you pass a variable of wrong type, the value still gets read into it as determined by the placeholder

• What if your code is correct, but user types in wrong type of input? (e.g. "Hello world" when you ask for an int)

• scanf also returns the number of items that were successfully read, so using techniques of next weeks you can read the input again

• scanf can also return special value EOF to indicate that you have reached the end of input stream 

Page 33: Lecture 2: Starting Out C Hello, world!. Our First C Program Since C programs are just raw text without any decorations, you can use any text editor you

 

"A programming language is low level when its programs require attention to the irrelevant."

Alan Perlis

"A programming language is for thinking about programs, not for expressing programs you've already thought of. It should be a pencil, not a pen."

Paul Graham