imperative week 2 and definitions expressions and more standard I/O Ritsumeikan University College of Information Science and Engineering Ian Piumarta 1 / 21
: typical #include <header-file.h>... // library, definitions global variable and definitions... function and definitions... int main() { main program code... 0; } Ian Piumarta 2 / 21
the CPU deals only with patterns of bits representing numbers the basic in C reflect this C has only two basic : numeric types (integers and floating point numbers) no value (the absence of any value at all) the numeric types are integers and floating point numbers the default integer type is called int it represents the natural size of integer arithmetic on your CPU on desktop / laptop machine, an int is usually 32 bits wide if you need to store larger values then use a long integer on a 64-bit processor, a long is usually 64 bits wide Ian Piumarta 3 / 21
every variable has to be declared before it can be used a variable declaration specifies the type of the variable the name of the variable optionally: the initial value of the variable written using the assignment operator = type name; type name = expression; one or more can be declared in the same declaration int a; int b= 2; long c, d= 3, e= 4, f; note that declared inside a function are local to that function declared outside any function are global Ian Piumarta 4 / 21
if no initial value is given, the variable s value should be considered unknown the compiler usually warns you about using an uninitialised variable main.c:10:15: warning: variable a is uninitialized when used here int a, b= a; ˆ pro-tip: always initialise your, even when you don t need to prevents nasty surprises when optimising, the compiler will remove unnecessary s Ian Piumarta 5 / 21
: arithmetic and relational C s should be familiar many in Python and Java are named after similar ones in C operator operation () function call putchar(42); highest precedence ++ -- increment and decrement ++x; * / % multiply, divide, modulus dow = day % 7; + - addition, subtraction sum = x + y; < <= > >= arithmetic relations while (x < y) x = x * 2; ==!= equal, not-equal if (getchar() == \n ) ++nlines; && logical and if (happy && know_it) clap(); logical or success = plana() planb(); = assignment a = 42; lowest precedence note: logical and/or a && b x && y // these are the ones you need most often are quite different to arithmetic and/or a & b x & y // these are for serious hackers which we will discuss further in a week or two Ian Piumarta 6 / 21
: arithmetic and relational note that equality == and assignment = are similar easy to write = when you mean == this is bad, because x = y is an expression in C what is wrong with this? if (c = \n ) ++nlines; pro-tip: avoid the above mistake by writing assignment asymmetrically (no space on left, one space on right) if (x == y) x= -y; // easy to see = and == are different putting constants on the left side of the == operator if (c = \n ) ++nlines; // what I spent a week finding and debugging if (c == \n ) ++nlines; // what I really wanted the program to do if ( \n == c) ++nlines; // much safer way to type what I wanted, because... if ( \n = c) ++nlines; // this causes a compile-time error (yay!) I used to spend hours finding if (c = \n )... (and similar) bugs since adopting the above style I completely stopped making this kind of error Ian Piumarta 7 / 21
: programs (function bodies) are made from sequences of expression : expression; any expression can be a statement: just put ; after it putchar(getchar()); // getchar() is an expression getchar(); // or a statement x == y; // useless, but legal ; // empty statement compound (blocks): {statement... } group zero or more into a single statement { // <--- beginning of block firstthing(); secondthing(); } // <--- end of block {} // empty (compound) statement {;;;;;;} // ditto {}; // beware: this is two! Ian Piumarta 8 / 21
: if (condition) statement if (condition) statement else statement control whether or not something is executed note: the parentheses around the condition are mandatory if (somecondition) dosomething(); // runs only if somecondition is true if (raining) stayhome(); else havepicnic(); // executed if it is raining // executed if it is not raining Ian Piumarta 9 / 21
: pro-tip: use compound in if, even when unnecessary if (raining) stayhome(); else havepicnic(); goshopping(); if (raining) { stayhome(); } else { havepicnic(); goshopping(); } // oops: will go shopping regardless of weather // ready for more if necessary // much safer! // no more shopping in the rain... and always when necessary for disambiguation! ambiguous else z() if a and not b z() if not a if (a) if (b) y(); else z(); if (a) { if (b) y(); else z(); } if (a) { if (b) y(); } else z(); Ian Piumarta 10 / 21
note: be careful with compound and semicolons : if (serioussecurity()) if (authorised()) {}; // do nothing else selfdestruct(); // when does this explode? nested if...else... can be confusing if (raining()) watchmovie(); else if (sunny()) sunbathe(); else walkdog(); pro-tip: format your code to make it more readable if (raining()) watchmovie(); else if (sunny()) sunbathe(); else walkdog()(); useful idiom: if (0) statement // temporarily disable statement Ian Piumarta 11 / 21
: while loop while (condition) statement; execute statement while condition remains true useful idioms: while (1) dosomething(); // repeat forever while (stillwaiting()) {} // do nothing while waiting while (stillwaiting()); while (stillwaiting()) ; // ditto, but maybe less readable // ditto, possibly an improvement Ian Piumarta 12 / 21
every function has to be declared or defined before it can be used a function declaration specifies the type of the result the name of the function a parenthesised list of zero or more parameters, separated by commas each parameter looks like a complete variable declaration optionally: the implementation of the function written as a compound statement type functionname(parametertype parametername,...); // declaration type functionname(parametertype parametername,...) { statement... } // definition a function can be declared any number of times but every declaration must be the same a function can be defined only once Ian Piumarta 13 / 21
pass zero or more arguments to a function when called function(expression,...) the argument expressions must match the declaration of function same number of arguments as declared parameters each argument type must match the corresponding parameter declaration int putchar(int c); putchar(); putchar("*"); putchar( x, y ); // as declared in stdio.h // bad: wrong number of arguments // bad: wrong type of argument // bad: wrong number of arguments putchar(42); // ok (but ignores result) int error= putchar( * ); // ok Ian Piumarta 14 / 21
the statement s a result from a function value; the type of value must match the function declaration C s other basic data type is void, which means no value at all if your function takes no arguments, declare its parameters as void if your function s nothing, declare its result type as void you can still use inside, but it must not have any value void byanymeansnecessary(void) { if (plana()) ; // yay success! if (planb() planc()) ; // try another tactic giveup(); // it s pointless } Ian Piumarta 15 / 21
more standard is performed on streams of bytes getchar reads one character from the standard input e.g., from your keyboard or from a disk file putchar sends one character to the standard output e.g., to your terminal window or to a disk file writing one character at a time is tedious, so we have... and puts("hello, world") ("hello, world\n") // write string and newline to output // write string to output Ian Piumarta 16 / 21
more standard puts does for strings what putchar does for is more complicated it can be called with more than one argument it sends each character in its first argument (a format string) to the output if it sees a %letter sequence within that string, it reads another parameter from the arguments that were supplied converts that argument into a string, and sends that string to the output for example %c converts an integer argument into the corresponding single character %d converts an integer argument into its decimal representation ("the character %c has integer value %d\n", 42, 42); ("the character %c has integer value %d\n",!,! ); produces the following output the character * has integer value 42 the character! has integer value 33 Ian Piumarta 17 / 21
more standard standard input and output can be connected to real when running a command, connect the standard input to a file like this $ command < input-filename and/or the standard output to a file like this $ command > output-filename warning: be very careful when redirecting output to a file if the file already exists, it will be deleted and then recreated do not type > file.c when you really mean < file.c! especially if you care about losing the contents of file.c Ian Piumarta 18 / 21
more standard imagine a program is reading from a file (not the terminal), then how does the program know when it reaches the end of the file? have values in the range [0, 255] getchar s an int value in this range when the input reaches the end of the file, getchar must somehow tell you use a sentinel value that is outside the above range use the sentinel value to indicate the end of file the value is given the symbolic name EOF EOF is a constant defined in stdio.h always check the value ed by getchar when getchar s EOF, you have reached the end of the file note: typing ˆD on the keyboard generates EOF Ian Piumarta 19 / 21
character tests the defined in ctype.h are useful when dealing with #include it at the top of your program, then you can call // these which non-zero (true) if c is... int isspace(int c); // whitespace (space, tab, newline) int isalpha(int c); // alphabetic (a letter) int isupper(int c); // an upper-case letter (A...Z) int islower(int c); // a lower-case letter (a...z) // or theses... which... int toupper(c); // convert c to upper case int tolower(c); // convert c to lower case run man ctype to see a (long) list of them all most of them have self-explanatory names, but if in doubt... run man isalpha (for example) to see an explanation of what it tests for Ian Piumarta 20 / 21
putting it all together how would you modify your program from last week to echo indefinitely, until the is reached? delete all the vowels from the input? print a summary of how many vowels were deleted? Ian Piumarta 21 / 21