0% found this document useful (0 votes)
13 views6 pages

Week 1

C is a widely used programming language that is compiled to machine code. It is statically typed with data types like integers and characters known at compile time. C is procedural rather than object-oriented. The pervasiveness of C is due to its use in operating systems like Linux and software like web servers. C standards now exist to promote compatibility, though C++ extends C with object-oriented features. Pointers are a key concept to understand in C programming.

Uploaded by

aakar845
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views6 pages

Week 1

C is a widely used programming language that is compiled to machine code. It is statically typed with data types like integers and characters known at compile time. C is procedural rather than object-oriented. The pervasiveness of C is due to its use in operating systems like Linux and software like web servers. C standards now exist to promote compatibility, though C++ extends C with object-oriented features. Pointers are a key concept to understand in C programming.

Uploaded by

aakar845
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps

Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

Outline What is C?
C is:
UNIX and C Programming (COMP1000) ▶ A programming language – one of thousands.
C at a glance
▶ Not the best, but perhaps the most important.
Lecture 1: Basics and Revision Revision ▶ An old language –
▶ Simple and primitive, powerful and pervasive.
Updated: 30th July, 2019 Jumps ▶ A compiled language –
▶ You write “source code”.
Department of Computing Functions ▶ Then, you convert it to “machine code” using a compiler.
Curtin University ▶ The machine code is the final program.
Copyright © 2019, Curtin University Expressions ▶ A statically-typed language –
CRICOS Provide Code: 00301J ▶ Strict data types: integers, real numbers, chars, etc.
C Programs ▶ These are known at compile time (“static”).
▶ A procedural language –
▶ Not object orientated – no classes or objects.
. . . . . . . . . . . .
. . . . . . . . . . . .

1/46 2/46 3/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

The pervasiveness of C Why use C? A very, very brief history


▶ As of July 2015, the Ohloh website tracked about 75
thousand C projects with 5.9 billion lines of code 1 .
▶ “C” itself is descended from other languages (most directly
▶ Well-known software written in C includes:
Because: from “B”).
▶ Much of a typical Linux distribution, particularly the kernel;
▶ Android — the mobile phone/tablet OS (based on Linux); ▶ It’s so widely used already (new graduates often have to ▶ For a long time, C was not well standardised — unlike Java,
▶ Apache — the web server software that runs the majority of maintain old code!). there was no single organisation in control.
the world’s websites. ▶ It’s very efficient (if you know what you’re doing). ▶ Incompatibilities arose between different implementations.
▶ Much more software is written in languages based on C: ▶ However, C standards do now exist — C89/C90, C99 and C11.
▶ It’s portable (to an extent).
▶ Microsoft Windows (C++).
▶ ▶ C89 (ANSI) and C90 (ISO) are the same thing.
Mac OS (Objective C).
▶ Mozilla Firefox (C++). ▶ C99 and C11 are minor updates.
▶ Google Chrome (C++).
▶ Internet Explorer (C++).

1 . . . . . . . . . . . .
https://www.ohloh.net/languages/c . . . . . . . . . . . .

4/46 5/46 6/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

C99 and C11 C++ What is there to know about C?

▶ The new versions — actually not very important. ▶ Pointers, pointers, pointers and pointers.
▶ A major extension to C, implementing object orientation (and
▶ You need to know the old C (i.e. C89/C90).
other interesting features). ▶ Engineering Programming (COMP1004) mostly skips around
▶ The old C is the lowest common denominator; used
everywhere. ▶ Very widely used, alongside C. pointers.
▶ If you want a “new” language, why use C at all? Use Java, ▶ Some features of C++ have been retroactively added to C. ▶ Pointers are the heart and soul of C — most of C’s more
C#, Python, etc. instead. ▶ Like C99, C++ will not be assessed in this unit! useful features are built on pointers.
▶ Unfortunately, some C books (e.g. Kochan) don’t say what’s ▶ That said, you also need to know about:
▶ However, the last lecture will discuss C++, and it is well
C99-specific and what isn’t. ▶ The structure of a C program.
worth learning. ▶ The environment (UNIX) in which you’re working.
▶ The lectures will briefly mention C99 features where relevant.

. . . . . . . . . . . .
. . . . . . . . . . . .

7/46 8/46 9/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

Things you should have seen before Remember variables and data types? Variable declarations
These are (essentially) the same in both C and Java: ▶ Each variable stores a single value, depending on its data type. ▶ Variables must be declared before they can be used.
▶ Symbols like semicolons (“;”), braces (“{...}”) and ▶ Simple data types include: ▶ A declaration consists of a datatype and a name:
parentheses (“(...)”). Signed integers: int, short, long. float number; /* Declaration */
▶ Simple data types (e.g. int, double, char). Unsigned integers: unsigned int, unsigned short, number = 5.0 * 2.5; /* Assignment */
▶ Variables and assignments (e.g. “int v = 42;”). unsigned long (cannot be negative).
Reals: float, double, long double. Here, number is declared (created) as a float (real number).
▶ Expressions (e.g. “v = 33 * x + z / 3;”). ▶ Declarations can also initialise variables:
Characters: char (letter, digit, symbol, etc.) –
▶ if, else, switch, break, default, for, while, do, return. technically a kind of integer. float number = 5.0 * 2.5; /* Same as above */
▶ Functions/methods; e.g. ▶ Mainly use int, double and char.
▶ Multiple variables can be declared at once, if they have the
double calculate(double x, double y) ▶ There are no classes or objects in C (unlike Java).
same data type:
{ ▶ Other special data types including pointers, arrays, structs,
unions and enums (which we’ll cover later). int alpha = 3, beta, gamma, delta = 6;
return x * y;
} ▶ C has strings, but no formal “String” data type (we’ll get to Here, alpha, beta, gamma and delta are all ints. Two of
. . . . that too). . . . .
them have been initialised. . . . .
. . . . . . . . . . . .

10/46 11/46 12/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

Variable names A small difference from Java Comments


Use comments to describe code in natural language.
▶ Should reflect the meaning of the variable!
How do you repeat something 100 times? Block comments
▶ Should be concise, but not too concise. Traditionally, comments are enclosed between /* and */
▶ In Java and C99 you can do this:
▶ Can contain letters (a-z and A-Z), digits (0-9) and
/* Speed of light
underscores (_). for(int i = 0; i < 100; i++) { ... }
(metres per second) */
▶ Cannot start with a digit.
▶ In C (in general), you cannot declare i inside the for int speed = 299792458;
▶ Case-sensitive (size, SIZE and Size are distinct names).
statement. Instead, you must do this:
▶ Cannot be a reserved word (auto, break, case, char, const,
int i; Single-line comments (only C99!)
continue, default, do, double, else, enum, extern,
float, for, goto, if, int, long, register, return, short, for(i = 0; i < 100; i++) { ... } In C99, single-line comments start with “//”.
signed, sizeof, static, struct, switch, typedef, union, int speed = 299792458; // Speed of light (m/s)
unsigned, void, volatile or while).
. . . but you can’t do this in C89.
. . . . . . . . . . . .
. . . . . . . . . . . .

13/46 14/46 15/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

Comments, meaningful names, indentation and whitespace Revision More Revision


Do you know how functions or methods work?
▶ It’s not just machines that read your code. The following code is valid in both C and Java. Take a minute to int addCubes(void)
figure out what it does. {
▶ Source code must frequently be fixed, updated, improved, etc.
int base = 3; int i, result = 0;
▶ This requires that humans be able to read your code as well.
int exponent = 19; for(i = 1; i < 5; i++)
▶ Comments help remind you, and explain to others, what the result += cube(i);
int result = 1;
code does and how it works. int i; return result;
▶ Meaningful variable names serve a similar purpose. }
▶ Indentation helps you see the code structure instantly. for(i = 0; i < exponent; i++)
▶ Whitespace helps you see words and numbers more easily. { int cube(int x)
result = result * base; {
▶ You must use all these — properly — to make your code return x * x * x;
}
readable! }
. . . .
. . . .
. . . .
. . . .
This will give you a result of 13 + 23 + 33 + 43 = 100. . . . .
. . . .

16/46 17/46 18/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

Jumps — return, break, continue and goto The break statement The break statement
▶ break immediately ends the current switch, for, while or ▶ Can also end a loop (usually from within an if):
do-while statement.
▶ Often used in a switch statement: while(...) {
▶ These statements jump to another place 2 .
...
▶ return and break are necessary in certain places. switch(...) { if(...) {
▶ Many advise against goto under any circumstances. case 1: break;
▶ Some advise against break (outside of switch) and ... }
break; ...
continue as well.
case 2: }
▶ Some advise against multiple returns in a single function. ...
▶ However, it’s worth noting what they actually do. break;
... ▶ This is not necessary — rearranging the if statement will
} achieve the same thing.
▶ break can lead to more compact code.
2
In fact, if, switch, for, while and do-while all jump as well, but they
. . . .
This is normal, and necessary. . . . . ▶ break can also lead to unreadable code. . . . .
provide structure to it. . . . . . . . . . . . .

19/46 20/46 21/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

The continue statement The goto statement Spaghetti code


▶ continue ends the current iteration of a loop. ▶ A relic from the bad old days, now very poor practice.
▶ Jumps back to the top of the loop, and continues with the ▶ goto simply jumps somewhere else, ignoring all the rules ▶ goto can easily turn your code into spaghetti:
next iteration, if any. about flow of control. ▶ Not clear what order things happen in.
▶ The target location is marked by a label — a name followed ▶ Very difficult to read, understand and fix — easier to throw it
while(...) {
... by a colon (“:”). out and start again.
▶ Your life will be miserable!
if(...) { while(x > 2.0) { /* Never, ever do this!! */
continue; theLabel: ▶ break and continue are more constrained, and so less
} x = x - 2.0; dangerous, but can still do the same thing.
... } ▶ Newer languages don’t have goto, for good reason.
}
evil ▶ However, in C, goto is sometimes used to separate error
▶ continue is never strictly necessary — if statements can if(x < 3.0) { handling code from the main algorithm, because C lacks
x += 5.0; exception handling.
achieve the same thing.
▶ Like break, continue can lead to more compact code. goto theLabel;
▶ Like break, continue can also lead to unreadable code. . . . .
} . . . . . . . .
. . . . . . . . . . . .

22/46 23/46 24/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

What is a function? C functions vs. Java methods Anatomy of a function


▶ C programs are broken up into functions.
The following example function takes (imports) a real number and
▶ Each function is a chunk if code, which may “call” (or returns (exports) either the letter L or the letter H.
▶ For those having studied Java, a function is very similar to a
“invoke”) other functions.
method. char indicator(float measurement)
▶ Functions are separate — they cannot contain one another.
▶ Just like a method, a function has: {
▶ Execution always starts with the main() function. ▶ any number of parameters (imports); char result = ’L’;
▶ When function alpha() calls function beta(): ▶ an optional return value (an export); if(measurement >= 0.5)
1. alpha is paused; ▶ its own set of “local” variables; and {
2. beta receives “parameter” values (data) from alpha; ▶ a chunk of code that performs a specific task. result = ’H’;
3. beta performs its task; ▶ However, functions are stand-alone, whereas methods occur }
4. beta optionally “returns” a value (data) to alpha; inside classes (and classes don’t exist in C). return result;
5. alpha resumes where it left off.
}
(Note: the words “call” and “invoke” always carry this precise
meaning. You cannot “call” anything other than a function.)
. . . . . . . . . . . .
. . . . . . . . . . . .

25/46 26/46 27/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

Historical interest Function calls and returns Function calls and returns
▶ Pre-1989 C had a different function parameter syntax: void calc(void) {
int someFunction(x, y) void calc(void) { ...
int x; ... int number = addTwo(5);
float y; int number = addTwo(5); ...
parameter
{ ... }
value (5) control
... }
} int addTwo(int param)
int addTwo(int param) {
▶ In modern C, this would be written as: { int result = param + 2;
int someFunction(int x, float y) int result = param + 2; return result;
{ return result; }
... }
The call:
}
▶ Function calc() calls function addTwo().
▶ The old form is still valid C, but rarely used. . . . . . . . . ▶ calc() pauses, addTwo() begins. . . . .

▶ param becomes 5.
. . . . . . . . . . . .

28/46 29/46 29/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

Function calls and returns The return statement Void


void calc(void) { ▶ Immediately ends a function — jumps back to the caller. ▶ Can show that a function does not return a value:
... ▶ Returns a value to the caller (if this function is non-void).
▶ Multiple return statements can lead to spaghetti code: void outputProduct(int x, int y) {
int number = addTwo(5);
control ... printf("The product is %d\n", x * y);
int badExample(void) { }
} if(...) return x;
return value (7) if(...) return y; ▶ Can show that a function has no parameters:
int addTwo(int param) return z;
{ void hello(void) {
}
int result = param + 2; printf("Hello world.\n");
return result; ▶ Try for one return only, on the last line: }
} int goodExample(void) { (Note: this void is sometimes omitted altogether, but
... technically that means “anything goes”.)
The return:
▶ addTwo() finishes, calc() resumes.
return result; ▶ void has a third use related to pointers, which we’ll discuss in
}
▶ number takes the value of result (7). . . . . . . . . a couple of weeks. . . . .
. . . . . . . . . . . .

29/46 30/46 31/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

Void returns The printf() function The scanf() function


▶ A void function, returning no value, needs no return
statement. ▶ Used to output text and other values.
▶ These functions hand back control at the end, automatically: ▶ A pre-existing function available for you to use. ▶ Used to input values (like the reverse of printf()).
void hello(void) { ▶ Works differently from the Java System.out.println() ▶ Described later in more detail.
printf("Hello world.\n"); method (but used for the same purpose).
} ▶ Described later in more detail. Example
▶ However, you can technically do this: int value;
Examples printf("Enter value: ");
void hello(void) {
printf("Hello world.\n"); printf("Hello world.\n"); scanf("%d", &value);
return;
(The printf() here is not strictly necessary.)
} printf("Coordinates: (%d, %d)\n", x, y);
▶ You can abuse void returns much like the other jump
statements, but you wouldn’t do that, would you? . . . .
. . . .
. . . .
. . . .
. . . .
. . . .

32/46 33/46 34/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

Expressions Statements that require expressions Function calls are values


/* Here we call beta and gamma, and then alpha. */
These statements all use expressions:
▶ Expressions occur virtually everywhere. alpha(beta(), gamma() + 3.0);
▶ someVariable = expression ; ...
▶ They are built up from: ▶ someFunction( expression1 , expression2 , ...);
▶ operands — variables, function calls and “literal” values;
▶ operators — +, *, >=, ++, &&, typecasts, etc.; and ▶ if( expression ) { ... } float beta(void) {
▶ parentheses — “(...)”. ▶ switch( expression ) { ... } return 5.0;
}
▶ They have a resulting data type, based on the operators and ▶ while( expression ) { ... }
operands. ▶ do { ... } while( expression ); float gamma(void) {
▶ Variables, function calls and literal values are syntactically ▶ for( expression1 ; expression2 ; expression3 ) { ... } return 7.0 ;
interchangeable.
▶ Variables and function calls are (generally) allowed anywhere ▶ return expression ; }
that values are needed. There are no limits to how complex expressions can be! (However,
void alpha(float x, float y ) { ... }
simpler expressions are more readable.)
. . . . . . . . Function calls can be part of any expression, just like variables. . . . .
. . . . . . . . . . . .

35/46 36/46 37/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

Function calls are values Function calls are values A simple C program
/* Here we call beta and gamma, and then alpha. */ /* Here we call beta and gamma, and then alpha. */
alpha(beta(), gamma() + 3.0); alpha(beta(), gamma() + 3.0);
... ...
#include <stdio.h>
float beta(void) { float beta(void) {
return 5.0; return 5.0; int main(void)
} } 10.0 (7.0 + 3.0) {
printf("Hello world.\n");
5.0 return 0;
float gamma(void) { float gamma(void) {
return 7.0 ; return 7.0 ; }
} }

void alpha(float x, float y ) { ... } void alpha(float x, float y ) { ... }


Here, beta() and gamma() are called first, and return their values. . . . . These values immediately become parameters to alpha(). . . . . . . . .
. . . . . . . . . . . .

37/46 37/46 38/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

Forward declarations Forward declarations (2) Forward declarations (3)


▶ In C, a function must be declared above its first use.
▶ If needed, you can place the function “prototype” at the top.
What’s wrong with this code?
Some terms:
void printSum(int x, int y) { Example ▶ A prototype consists of the name, parameters and return type
printNumber(x + y); of a function.
} void printNumber(int number);
▶ A forward declaration gives the prototype by itself (usually at
void printSum(int x, int y) { the top of the source code).
void printNumber(int number) {
printf("%d\n", number); printNumber(x + y); ▶ A function definition gives the prototype and the actual code.
} } (You can sometimes just re-arrange the order of the functions, but
this is often inconvenient or even impossible.)
In C, the order of declaration is important (unlike Java). void printNumber(int number) {
printf("%d\n", number);
}
. . . . . . . . . . . .
. . . . . . . . . . . .

39/46 40/46 41/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

C program structure C program structure Compiling your C programs


#include <stdio.h> ▶ In Java you use javac.
▶ In C you can use gcc, though there are many alternatives.
void bananas(int n); ▶ To convert your source code (prog.c) into an executable
double mangos(void); program (prog):
▶ A C program consists of one or more files. [user@pc]$ gcc prog.c -o prog
int main(void) {
▶ Each file contains one or more functions.
... ▶ “-o name” gives the output filename.
▶ One file contains the main() function. return 0; ▶ Without it, the executable will be called “a.out”, which is silly.
} ▶ There are other options as well; e.g.
▶ -Wall turns on “all warnings”.
▶ -ansi turns off C99 extensions (leaving C89 only).
void bananas(int n) { ... }
▶ -pedantic turns on additional checks for C89 compliance.
▶ These options help you produce better, more portable code.
double mangos(void) { ... }
... [user@pc]$ gcc -Wall -ansi -pedantic prog.c -o prog
. . . . . . . . . . . .
. . . . . . . . . . . .

42/46 43/46 44/46


C at a glance Revision Jumps Functions Expressions C Programs C at a glance Revision Jumps Functions Expressions C Programs

Running your C programs That’s all for now!

▶ Unlike Java, C programs don’t (typically) run on a “virtual


machine”
▶ You don’t need any other software installed, except for: ▶ Make sure you attempt the pre-lab exercises before coming to
▶ the operating system class.
▶ any libraries your program uses (via #include) ▶ If you have any uncertainties, please see the lecturer or unit
coordinator ASAP!
Example
[user@pc]$ ./prog

. . . . . . . .
. . . . . . . .

45/46 46/46

You might also like