COSC 2P91 BasiCs Week 2a Brock University Brock University (Week - - PowerPoint PPT Presentation

cosc 2p91
SMART_READER_LITE
LIVE PREVIEW

COSC 2P91 BasiCs Week 2a Brock University Brock University (Week - - PowerPoint PPT Presentation

COSC 2P91 BasiCs Week 2a Brock University Brock University (Week 2a) BasiCs 1 / 24 Reminder on C source code Though far less-so than many newer languages, C is still fairly portable . It still needs to be compiled for different target


slide-1
SLIDE 1

COSC 2P91

BasiCs Week 2a

Brock University

Brock University (Week 2a) BasiCs 1 / 24

slide-2
SLIDE 2

Reminder on C source code

Though far less-so than many newer languages, C is still fairly portable. It still needs to be compiled for different target architectures and platforms, so program behaviour may not be consistent Typically programs will rely on platform-dependent libraries (for the sake of simplicity, we mostly won’t concern ourselves with the different versions of the C specification)

Brock University (Week 2a) BasiCs 2 / 24

slide-3
SLIDE 3

Variables

Variable declaration is done in effectively the same means as in Java

◮ Scope and extent rules are mostly the same

Declaration of a variable is sufficient for memory allocation

◮ Outside of dynamic allocation, of course

External variables (declared in the outer level of the file) persist for the entire execution

◮ We’ll be returning to this again a bit later ◮ External variables can also be implicitly or explicitly made available

within procedures

By default, variables declared inside procedures are automatic

◮ Allocated upon entering the block ◮ Deallocated upon exiting the block ◮ Allocated on the stack Brock University (Week 2a) BasiCs 3 / 24

slide-4
SLIDE 4

Variable Names

Allowable variable names follow fairly typical rules: Alphanumeric characters Must start with a letter Spaces aren’t allowed, but underscores are Reserved words are... reserved Names are case sensitive

◮ But don’t be “clever” with that knowledge

If you’d like to declare multiple variables of the same type, it’s done the same as in Java:

i n t i , j , k=3, kwyjibo ;

Brock University (Week 2a) BasiCs 4 / 24

slide-5
SLIDE 5

auto vs register

As already mentioned, variables declared within blocks are automatic implicitly.If desired, you can explicitly declare this by using the auto

  • modifier. Another alternativ

If desired, you can explicitly state this via the auto modifier

◮ Note: unlike Java, you generally can’t expect an automatic variable to

be initialized to some specific value (e.g. 0)

◮ If you want a variable to have a specific value, give it that value!

Alternatively, the register modifier will add a hint that the compiler should try to ensure that the variable is assigned to a register in the CPU

◮ Depending on the amount of optimization employed by the compiler, it

might do this by default anyway

◮ It still potentially starts with ‘junk data’, so initialize it before use ◮ Note the word try; it isn’t a guarantee that a register will be available!

Let’s look at an example!

Brock University (Week 2a) BasiCs 5 / 24

slide-6
SLIDE 6

Constants

Obviously, peppering your code with literals isn’t ideal if it can be avoided. This is especially true if you’re using the same value more than once (and each instance will always be the same value as each other). In these cases, some form of constant is probably more appropriate. #define can be used to define a replacement for the preprocessor

◮ e.g. #define PI 3.14 will tell the preprocessor to substitute the

literal 3.14 for every instance of PI within the code

⋆ By the time it gets to the compiler, it’s just 3.14 ◮ Some swear by this technique, but it completely obliterates the concept

  • f scope, so you might want to go with the alternative

const defines a variable as being a constant

◮ The compiler may make use of the knowledge that this value won’t

change

◮ Of course, since you can’t change it later, remember to initialize it in

your declaration line

◮ Note: don’t ignore warnings. Seriously. Brock University (Week 2a) BasiCs 6 / 24

slide-7
SLIDE 7

static

There are two basic uses for the static keyword: A local variable (declared in a block) that’s declared static is not deallocated upon leaving the block

◮ This means you can use it to retain data across invocations of the

same procedure

A function or global variable declared static will become inaccessible

  • utside of that source file

◮ Think of it as being roughly analogous to private in Java Brock University (Week 2a) BasiCs 7 / 24

slide-8
SLIDE 8

volatile

It doesn’t seem likely that this will be used much in this course, but adding the volatile modifier acts as an indication to the compiler that a variable might be externally modified. There are two situations in particular where this may be relevant: If the program is threaded, and another thread might be making changes to the variable, then the compiler should know to not rely on it still maintaining the last known value

◮ Java has this feature, too, for effectively the same reason

If the compiler would normally employ optimizations that relied on the presumption that the provided code was the only source of changes to the variable — but that wasn’t really the case — that would be... bad

◮ Consider cases where external programs or hardware could be manually

changing the variable’s value

Brock University (Week 2a) BasiCs 8 / 24

slide-9
SLIDE 9

Scope

For the most part, C follows the same scope rules as Java (and other C derivatives). Global

◮ Declared in the outer level of the source file (outside of any blocks) ◮ May be accessible within any procedures within the file, if a new local

variable with the same name is not also declared within the procedure

⋆ Again, global variables to be used locally may be explicitly declared as

such via the extern modifier

Local

◮ We’ve already discussed this ◮ Let’s look at an example, showing why it’s advisable to declare all local

variables at the beginning of the procedure...

Brock University (Week 2a) BasiCs 9 / 24

slide-10
SLIDE 10

Types

There are several types available for use: int

◮ short int (or short) ◮ int ◮ long int (or long) ◮ long long int (or long long) ◮ sizeof(short)≤sizeof(int)≤sizeof(long)

char Floating point

◮ float – typically 32 bit ◮ double – typically 64 bit ◮ long double is also a thing, but less common

Both char and int types can be signed or unsigned. Literals can be long if ending with L, and unsigned when ending with U Of course, unsigned long values are possible with UL

Brock University (Week 2a) BasiCs 10 / 24

slide-11
SLIDE 11

Type conversions

Of course, binary operators normally only make sense when both operands are of the same type. You can explicitly cast values:

i n t i ; double d =3.6; i =( i n t ) d ; p r i n t f ( ” i c o n t a i n s : \%i \n” , i ) ;

What about this?

i n t i , j ; double d ; i=d=j =3.6; p r i n t f ( ”\%i \%f \%i \n” , i , d , j ) ;

Brock University (Week 2a) BasiCs 11 / 24

slide-12
SLIDE 12

Simple IO

printf

Proper IO is a topic for another time, but we’ve already seen enough basic IO that it’s probably a good idea to make it a bit more official: printf – print formatted

◮ Accepts a String as its first parameter ◮ The string may contain special markers for where to insert

substitutions

⋆ All such substitutions are provided as additional arguments ◮ Common tokens: ⋆ %d or %i – int ⋆ %ld or %li – long ⋆ %f – float ⋆ %lf – double ⋆ %c – char ⋆ %s – string ⋆ %x – formatted as hexadecimal ◮ Don’t forget common special characters (\n, \t, etc.) Brock University (Week 2a) BasiCs 12 / 24

slide-13
SLIDE 13

Simple IO

scanf

scanf is the complement to printf; it reads input from the user, using the same style of formatting tokens The biggest difference comes from the fact that we may wish to receive multiple values — but C doesn’t allow for multiple returns from a function — so we need to get a bit “clever”

◮ Essentially, we need to allow the procedure to gain direct access to our

local variables

⋆ This requires the use of a pointer, which we’ll explain in greater detail

at a later time

It’s worth noting that actually using scanf for multiple values at once might be more trouble than it’s worth

◮ It doesn’t cooperate very well when it encounters text formatted at all

differently from expected

Brock University (Week 2a) BasiCs 13 / 24

slide-14
SLIDE 14

Arrays

Arrays in C are handled very similarly to other languages, but aren’t quite as flexible. You can still declare them

◮ e.g. int dealies[10]; ◮ Note that the square brackets must come after the variable name; it

isn’t integrated into the type in C

You can also pre-initialize them automatically

◮ e.g. int dealies[]={1,2,3,4,5};

However, dynamic allocation is substantially more complicated (and thus saved for a later date)

Brock University (Week 2a) BasiCs 14 / 24

slide-15
SLIDE 15

Multidimensional arrays

So long as you still aren’t allocating them dynamically, they’re still created “in the usual way”. However, don’t even bother attempting ragged arrays yet The compiler will need to at least know the number of columns

Brock University (Week 2a) BasiCs 15 / 24

slide-16
SLIDE 16

Strings

Unlike some other languages — e.g. Java — strings in C aren’t really anything special; they’re just arrays of characters. However, consider some of the common uses for strings: Data read from a file Data read from a user These might not allow for knowing the precise number of characters in advance; that requires figuring it out during execution. But wait, we aren’t dealing with dynamic allocation yet... that means

  • verallocation is required!

◮ i.e. creating a static character array with more than enough space for

the expected input

◮ So, how do we know how much of the array to use?

Strings may be initialized in the conventional format (with quotation marks), or explicitly as any other array is initialized The string library (string.h) includes several helpful tools.

Brock University (Week 2a) BasiCs 16 / 24

slide-17
SLIDE 17

Booleans

As already briefly discussed, we don’t really have a boolean type. We could effectively create one if we wanted, but that probably isn’t necessary. Recall that 0 means false, and anything else means true However, be careful! ~0 != !0, but both are not false! This starts becoming particularly problematic when booleans are calculated in different locations in the code (especially in different files) and when relying on bitwise operations (particularly for bit flags)

Brock University (Week 2a) BasiCs 17 / 24

slide-18
SLIDE 18

Labels and goto

There may (don’t do this) be limited cases (but not for you) where one may (don’t do it) need to explicitly (don’t even think about it) jump to a specific (no!) place in the code (or not). Mark a potential target of such a jump via a label — some word ending with a : Jump to that target via the goto command Really, try to avoid these whenever possible They’re occasionally used to break from outer loops (when in nested loops), but can seriously hurt readability and might lead to unintended side effects if some code that would normally execute is skipped.

Brock University (Week 2a) BasiCs 18 / 24

slide-19
SLIDE 19

Conditionals

Other than not having an explicit boolean type, if statements work pretty much the same as in Java. Like Java, we have if and else There is no explicit then or elif For if or else, only the next statement is attached as the consequence unless you use a block instead. And, of course, watch out for semicolons

◮ (mwahaha) Brock University (Week 2a) BasiCs 19 / 24

slide-20
SLIDE 20

Dangling elses

One small thing to watch out for nested conditionals is the concept of a dangling else. Consider the following code:

i f ( a ) i f ( b ) puts ( ”Yes , a and b” ) ; e l s e puts ( ”Uh . . . help ?” ) ;

Languages like, Ada and Bash script, use explicit terminators for conditionals (like end if and fi, respectively)

Brock University (Week 2a) BasiCs 20 / 24

slide-21
SLIDE 21

Ternary conditional operator

p r i n t f ( ” This i s ” ) ; p r i n t f ( remember last week ?” easy ” : ” c o n f u s i n g ” ) ; p r i n t f ( ”\n” ) ;

Brock University (Week 2a) BasiCs 21 / 24

slide-22
SLIDE 22

Switch blocks

In C, switches can operate on an integer or enumerated type, to effectively act as a simplified if-then-elsif construct. For example:

switch ( d e a l i e ) { case 1: p r i n t f ( ”Only run t h i s

  • n 1\n” ) ;

break ; case 2: case 3: p r i n t f ( ”Run t h i s

  • n 2 or

3\n” ) ; break ; case 4: p r i n t f ( ”Only run t h i s

  • n 4 ,

but continue to 5 , too \n” ) ; case 5: p r i n t f ( ” I ’m a 5\n” ) ; break ; d e f a u l t : p r i n t f ( ”Catch−a l l f o r e v e r y t h i n g e l s e \n” ) ; break ; // because I can }

Brock University (Week 2a) BasiCs 22 / 24

slide-23
SLIDE 23

Loops

Anything here we’re not familiar with? for “for-ever” while do-while break and continue

Brock University (Week 2a) BasiCs 23 / 24

slide-24
SLIDE 24

Questions?

Comments?

(insert joke here)

Brock University (Week 2a) BasiCs 24 / 24