Systems

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Symbolic constants

#define can be used anywhere a literal const can be used, but constants defined with the const key word can only be ised where variables can be used. Is a name that subsitutes for a value that can not be changed. Can be used ot define a constant, statement, mathematical expression

What does #define do

#defines is a macro, a preprocessor directive that is replaced with code that are defined to represent

Preprocessor directives examples

#include #define

What does #include do

#includes is a preprocessor directive that has its contents replaced with its specified libraray file

What are the automatic variables(4 of them)

$@, $^, $<, $*

Patterns: and what it means

%, make wildcard, specifies a pattern

print 4 decimal places print 4 digits in size

%.4f %4.3f

Using patterns: and why that command

%.o:%.c *.h [tab] gcc -std=c99 -pedantic -Wreturn-type -Wformat -g -c $< -o $@ We use this bc makefile defaults to using cc and not gcc, to build .o files. cc wont give any warnings the way gcc will with the 4 warning flags we give it This doesnt deal with header file dependencies This rebuilds all .o files when we touch any .h file. Needs to have at least one .h file for in the directory for this to work right or it defaults to cc again. If we change only one .c file, it only rebuilds the one matching .o file.

How to get an address of a ptr

&

example of address math(this is what the compiler does)

&p[0] + (3* (sizeof(int)))

IMplicit type casting and promotion

('a' - 32) = 97 -32 = 65 Smaller type char is promoted to be the same as as the interger size int. Determined at compile time No infformation lost when converting from type to comparable larger type

Explain the compilation or (build) system

*This process runs in memory** 1) Our program takes in a program source code, a .c files using an editor of our choice. The source file is jsut plain text We run %gcc -o hello hello.c to begin the compilation, and building system 2) Preprocessor takes in a source file and .h file. Obeys the commands that start with #, aka Looks at all the preprocessor directives. Replaces all the macros with the code each maco is defined with, then goes to the area on the disk where the library files are. Gets a copy of the library's contents. Then replaces all the contents of #includes with a copy of the specific library's contents. Then outputs a .i file Summary: Takes .c and .h to create a .i file. .i file is the ulitmate source code where in a .i file, all the #includes are expanded and #defines replaced 3) The compiler takes the .i file outputed by the preprocessor and generates assember source code, which is a .s file 4) The assembler takes the output of the compiler, the .s file, which is assembler source code and convert the assmeber code into pure binary/machine code. Which is going to be object code and output a .o file Summary: Takes in a .s file and outputs a .o file. The .o file is fragments of machine code with unresolved symbols, ex some adresses that are not yet known(vars/subrs) 5) Linker takes the .o files and merges all the object code from multiple modules into one. If we are using functon from libraryies, the linker will also link our code with the library function code. This will output a executable file Summary: .o and library links a.out, and resovles symbols, and generates a executable Static linkage: linker makes a copy of all used library functions to the executable Dynamic linkage: Code is not copied, it is done by just placing the name of the library in the binary .o file. 6) The executable executes the program

which has higher precdence *& or -> .

-> . has higher precdence.

Left shift how many ways?

1 kind

Format Strings for: 1)single character 2)signed decimal integer 3)signed floating point value in E notation 4)signed floating point value 5)signed value in %e or %f formate whcihc ever is shorter 6)unsigned octal, base 8 integer 7)string of text, null terminated 8)unsigned decimal integer 9)unsigned hexadecimal base 16 integer 10)percent character

1) %c 2) %d, %i 3)%e 4) %f 5) %g 6)%o 7) %s 8)%u 9) %x 10 %%

Pointer rules

1) A pointer stores a referance to its pointee, the pointee in return stoess smthign usefule 2) The dereferance opeation on a pointer accesse it s pointee, a pounter mauy only be derederence after it has been assiedn to refer to a pointee. 3) Allocatting a pnter does not automatically assign it to refer to a pointee,Assigning the pointer to refer to a specific pointee is a speraprte operation 4) Assignment between two pointers make then refer to the same pointee wihch introduces sharing. a pointee is a varaible whose address is assigned to the value of a pntr

Make can do more than c code: What can it do?

1) Can be used to issue any command in linux 2) follows the riles to build the target specified on the command line 3) It will run those commands if the target is older than any of the things it depends on

Passing pntrs: how to change a variable in a calling function

1) Dont pass the variable itself, pass by vlaue walways gives the function a copy. 2) So we will use a pntr instead. 3) Pass the address of the variable we want to change using & 4) the type of the parameter has one more * than the variable we want to change 5) The called funct puts one * on the param when it wants to use or change the variable in the calling function.

What does the preprocessor do:

1) Goes to the area on the disk where the library files are kept. 2) Then finds the files with the names stdio.h and stdlib.h 3) Once it finds those files, it will then replace the directive # on the source file, with a copy of the contents in the specified header file.

Precedence:

1) Parentesis () 2) Function call () 3) Subscript [] 4) struct member . 5) struct pointer to member -> 6) Post increment p++; 7) logical negation ! 8) Unary PLus + 9) Prefix increment ++p; 10) Indirection/dereferance * 11) Adress & 12) sizeof 13) type conversion/casting (type) 14) multiplication * 15) additon + 16) left bitwise shift << 17)right bitwise shift >> 18) equal to == 19) bitwise AND & 20)logical and && 21) assignment = 22) comma ,

Two basic types of I/O

1) character based 2) formatted

Things to know about makefiles

1) directory matters, 2) 1 makefile per directory 3) Unforgiving when it comes to whitespace 4) each command must have a tab b4 it and is immedietyl followed by hitting the enter key. 5) Must be in the directory of the makefile to call make 6) make is a linux/unix utility 7) tag name is also called section name 8)IMPORTANT: all children must be younfer than their children, aka all new files must have a more recent date.

Which one of these is broken code but will compile Which one doesnt compile Which one codes defensively if(tokens == 6) if(tokens = 6) if(6 == tokens) if(6 = tokens)

1) if(tokens = 6) 2)if(6 = tokens) 3)if(6 == tokens) bc the left side cant be assigned

4 warnings and what they mean*

1) std=c99 : lets the compiler know that we are using the compiler version c99 2) -pedantic :tells gcc to issue warnings 3) -Wreturn-type : give errors about function return types 4) -Wformat : for scanf and printf

2 kinds if data "strings" in C

1) string literals which are read only strings as they are stored in read only memeory 2) Strings which are arrays of characters which are read-write strings. They are stored in read-write memory.

how does The compiler turns pointer math into address math by scaling:

1) the compiler needs type to get size to do the scaling 2) the programming model says memoory is is byte addressable 3) the compiler needs to generate a byte addess

size of long double

10 bytes

size of short

16 bits, 2 bytes, 1 nibble

Right shift, how many ways? What are they

2 kinds: Arithmatic shift Logical shift

Declaration of constants

2 ways: 1) Put const keyword after the type keyword or before the type keyword **Any assignment to these variables declared const is invalid. So the declared const must be initalized with its constant value as part of the declaration bc the compiler will not allow statements to make assignements to that const variable later. Ex: float const NUM = 2.121313f; const float NUM = 2.123123f; It should be treated as a read-only variable ** Upper case is used for decalred constants and for thsoe with #define

B2T

2's complement, signed binary

redirection of what? 3 things

3 file descriptors that are explicitly defined to represent 3 distinct data streams stdin(0) standard input stdout(1) standard output stderr(2) standard error

Size of float

32 bits, 4 bytes

size of int

32 bits, 4 bytes

size of long

32 bits, 4 bytes

Size of double

64 bits, 8 bytes

Size of a pointer

8 bytes

Q: If i have a pntr to a long, and I increment it by 1, how much did the value change that gets stored. How much getts added to the stored vaule?

8 bytes bc long is 8 btyes

Relational operators

< <= > >= == !

Differences between definition and declaration

A defintion is type information only and no values. A declaration is type inforamtion and value information For variables: Def: tells the compiler the type of the variable and its inital value. And is declared only once Dec: Tells the compiler the type of the variable and is declared only once For funct: Def: Is decalred only once and tells the compiler its return type, param type, the code of the function. Dec: Only tells the compiler the type information, type of param and return type. Can be declared mutliple times as long as the all the declarations are identical to the repspective types. **IMportant : Definitions are also declarations bc it provides the compiler with type information

Decalring functions

A fucntion must be declared bu not nessecaruly defined before it can be referanced in a non declaribed statment, which means it mist be declared before being called or invoked.

What is a proper declaration for a function

A proper function declaration tells the compiler only the type information and no values. Can be declared more than once as along as the declaration are idenctical w respect to type

Declaring variables

A varibale must be declared but not necessarily defined befroe it can be referanced in a non-declariave statement

how to make constant decimal be a float?

Add f

Why we need to know more than the address for pntrs

All the addresss sayss is start here, but somebody needs to tell the compiler how many bytes and type information(given by us)

File scope

Any function declared in a file can be called from anywhere in the same file, AFTER the point at which it is declared.

Why is type important

At the lowest level, data is a bit pattern, that means it can have mulitple interpreations depending on the type of data it encodes. In the cpu, instructs which perform a given type of operation on data of different types are different instructions Wehn the compiler generates instructions for the cpu to accesss a value in memoiry, it does not make any assumptions about how to interpret that value(the bit patter). We must explicitly tell the compiler the type of the value stored there with type in a declaration or with a cast, s.t it can generate teh appropriate type of instruction for the CPU

To remeber when doing B2U and B2T and HEX conversions

B2U will always be the positive value of the binary bits regardless of 1 being in the most sig place B2T will follow as normal w 1's indicating negitive HEX: Will follow B2U with remaining positive, and use LETTERS after 9.

Why can arrays work w subscripts

BC all the elemebts are of the same size and type and are stored at contiguoys locations in the memory

In-Band Signaling

Band Signalling is when the return signal isn't big enough to represent all of the possible values that something can return. For instance, getchar() returns an int because a char doesn't have an EOF character already within ASCII, so it must return an int because otherwise, it couldn't return this value.

Shift this to the left by 2 places: Binary Value: 01110101

Binary Value: 01110101 A: 11010100 Shift the values to the left by 2 and adding 2 0's at the end

Explain this: char *string1 = "go bucks" char *string2[10]= "go bucks"

Bith values stoted in each of the indivual character will end with a null at the end of the string both "go bucks" are read-only memory string1 is read only memory String2 is a read-write string bc it is stored in ordinary memory so we can modify this.

How does stdin , stdout, stderr work on linux/unix

By default, UNix/linux, c programs read input from standard input (stdin) usually from the keyboard and write output to standard outpout "stdout" usually thr screen. Unix/linux error msges go to "standard error" stderr also the screen

C allows direct ____________, example of this is

C allows direct manipulation of memory. example of this is pointers

C and enums

C doesnt have control over its enums

C has what instead of methods

C has functions

C is _____ and is not_____________

C is procedural and not OOP

Cache Coherency

Cache coherency - two copies that must always match. Main memory (the DRAM chips) and the three levels of on-chip cache can never be caught out as having different values. Saying to the conductor, "there are six of us" and handing him seven tickets. One of those is wrong, they must match

C and its variables

Case sensitive. ex num and Num, C counts this as 2 seperate variables, Not a good paractice.

Four general categpries of statements in languages: Arithmetic/Logical Operations

Compare something, calculate something Ex: int x; x = 5*5;

Size of a statically allocated array

Compiler is smart enough in the function that defines a static array to tell you how big it is but no other function would be able to do so. BC ONCE YOU PASS THINGS YOU LOSE TRACK OF HOW BIG THINGS ARE, BC IT COMES IN A AS A PNTR

What is const on a struct

Const on a struct is the same as const on a pntr, so that means we use const in order to ensure that the values of the struct dont get modified.

The Bigger Picture: What are the Four general categpries of statements in languages

Declaration(optional in some languages like python) Data Movement Arithmetic/Logical Operations Control Flow

Default stoarge class

Depends on where it is decalred. Automatic stoarage class

What does C not have:

Does not: 1) Suppoet the notion of classes or objects 2)Support encapsulation, all memory is technically accessable and modifiable by any instruction of an executable 3) C NOT OOP AND IS PROCEEDURAL 4) NO garabage collection

Anything particular about enums that you cant that you cant do with ints

Dont assign an int to an enum variable

-Wformat

Errors indicating wrong type, but code will still compile

Compile time

Events that can occur when a program is being commpiled or built These events are known as static

Run time

Events that occur when the program is actually being executed or running These events are known as dynamic

Indirect member access

Ex: (*p).member

What kinds of names have linkage?

File scope names have linkage and only file scope names have linkage.

Arithmatic shift

Fills in the left with a copy of the most signifigant bit. EX: Value: 1110101 shift right 1 bit: 1111010 shift right 2 bits: 1111101

How does bitwise work

For bitwise &, We multiply the binary values of the two variables we are anding togetther. This returns us a bit value

Cash coherency

Gives vocabulary to discuss a whole range of porvlems that are consistent w each other/ similar with each other.

Naive string copy

Gonna assume that theres enough space in the destination and that the source is a well termined string.

Self referantial structs , illlelgal and legal and why

Idea is : Cant put your own car in the truck of your car but we can put a pntr to ut. so struc a{ struct a hello; } This is illegal bc the struct contans its own members and the struct inside contains it own members and the struct hello inside that struct contains its own members and its an infinaitly recursive. that illegal but this is legal: struc a{ struct a *hello; } Legal bc the struct does not contain a member that is another struct of the same type. But reather a pntr to a struct of the same type

About struct passing

If you get a struct, and you pass a vanilla struct, it gets copied and a copy of the struct gets passed

What storage class does parameters have

In function declarations: prototype In function definitions: automtic, locatied in stack and can not be changed

What are Basic Datat types:

Integer types Floating point types

The structs w the same meber list and no tag, with variable lists are declared in the same program: will this work ? z = &x y[2] = x

Invalid, compilation will fail, and compiler will give error, thisis bec the 2 stuctures are in differnt memory spaces. X is of a different type than elements of y and type *z is also different from the type of x

How makefiles work:

It creates a dependency table, so if one .h file changes, and .h is a dependy of all the targets,then all files will change.

How does make know when to regenerate targets

It does this by comparing the target file modification times.

Structures as function arguments

It is legal to pass a struct as a variable to an argument to a func. This is a bad idea bc if the stack is large, bc the parma are passed by value in C, all of the values of the member si nthe stuct is copied and pushed onto the stack when the functions are called. However if we pass pntr to a struct, then only the value of the pnter is passed, pushed to stack rather than all the members int he struct.

Where is a block scope variable location in memory?

It is located on the stack

What is a definition

It is the type information and value. For a variable : it tells the compiler the type of the variable and the intial value. Can only be defined once in a C prgram For a function: it tells the compiler the return type, parameter types. and the code that should be executed when the function is called. Can only be defined once in a C program **A definition is also a declaration bc it also contains type information

Explain how pointers work

It says, go to the address you pnt to , and pull up as many bytes as the thing that you pont to is and return. The returend value is the value of te expressson

Purpose of make

It's purpose is to determine automatically which pieces of a large progam need to be recompiled. It then issues the commands necessary to recompile them.

What needs to appear on the left side of an assignment operator

L value: a location memory

little endian

Least significant bytes first if the lowest order byte pnts to the lowest address, it is a little endian

Shell redirection **needs more work on this**

Left side of the redirection goes to where the right side of the redirection currently goes.

What is make?

Make is a utility used to build and maintain groups of programs from and other types of files from source code. Make builds an executable.

When to use arithmatic right shift

Make sure that the number is cast with a sign. So if we take an unsigned int , cast it as an int, and shift , it will give us arithmatic shifting.

Four general categpries of statements in languages: Data Movement, and example

Moving data around: variables are passed to functions and are copies of one another bc C is pass by value. Basically to move around bits, change new bits for old 1) Memory to function variables 2) Function variables to function variables 3) Function variables to memory example: payRate = payRate * 1.01;

How to use make

Must create a makefile that describes the relationships among files in your program

Main() in C

Must have 1 in every C program Programe exectuion always begins in main Mian deos not have to be first func defined in the program

Is a function declaration without any information about the arugments a protoype? Why

No because a protypeu need information about the number, and type of arguments ino order to be a prototype.

character based I/O

No format specifiers, getchar() putchar(c) this is output

String length

No function to tell us its size and we dont need one either, bc string is null terminated. Do not count null when counting string length. We do need 1 more than the string length when deriving how much stroage we need

Does passing a refereance get around pass by value

No only pnters can get around it

What makes void pntrs diff than other pntrs

No type. cant dereference, hold any addresses bc no type. Can not be dereferenced without casting. Can not be used to get the contents of another memory location without casting

Logical operators

Non-Zero is true 0 is false

What is not valid to do w funct ptr?

Not valid to Assign the address of a function which has a different return type of fp, not valid to assign the address of a func which as different params, either in diff order, or diff types or number. In short signitures must match

The differences between malloc and calloc

One of them does more than the other, calloc initalizes to 0 while malloc does not. For both need to heck if it fails, one your done using the vlaue, free it. Dont use the same pntr after you freeed it and dont lose the last pntr to rhe dynamically allocated spcae. Only a handful of errors posisble but lots of ways to the make the erros.

Four general categpries of statements in languages/ Control flow

Procedure/function calls Looping Conditions

Emplicit type casting

Purposely converting one variable to another data taupe

Four general categpries of statements in languages: Declaration

Python: Faster Sometimes its good, sometimes its bad. Easy to make mistakes if no variable decalration in language Example: int x;

What needs to appear on the right side of an assignment operator

R value: a numerica value which can be stored in binary form

Precedence

Relationship between two operators in terms of the order in which operatiosn are performed We can always enforce a precedence different form the precedence specified using paraentesis Is a binary relation.

Associtivity

Relevant only if two adjacent operators have the same precedence. In this case, Left to Right associtivity. This means the left operator is done first, then the right most operator. Ex: num1 = 2.0/1.0/2.0 This is going to calculate from left to right first.

What are unsequenced side affects and rules about side effects

Rule about side effects: Only have 1 side effect for 1 storage location at a time

How does logical operators work

Same as java: For &, both need to be true to be true.

what does extern do

Says, this is a declaration, not a definition, someone else carries the definition We use extern keyword to decalre a filescope varuabke when we dont want to define it. Helps assures that there is a single definition for a variable

Logical shift

Shift left with 0's Value: 1110101 shift right 1 bit: 0111010 shift right 2 bits: 0011101

Over loading the word static, give exampels

Static has different meanings depending on context static storage static arrays static @ changing linkage

How are strings stored

Strings are stored as sequences of characters in memory(aka char arrray) Because it is a char array, the individual characters will always be stored in a contigous bytes memory

Do string need a size?

Strings don't need a size bc we know they are null terminated

Where are structs in memory

Structs are stored near each other but they are not guarenteed to be indentically nex to each other.

Global and local are not correct terms for storage calss, scope or linkage

T

Most languages hid the address

T

address can be called as a referance but it is nnot c terminology

T

Preprocessor

The first program called when you build C source code.

what does a func pntr pnt to and what deos it store

The func pntr points to the begining of the code of a function it pnts to a function it stores a addess of a func

Indirect member access

The function must dereferance the pnts and can use Ex: (*p).member or p->member

Explain this: char *string2[10] = "go bucks"

The individual chars in str2 are variables (we can change the chars in the string, so the elements in string2 can be treated as if they are in other arrays. String2 the identifier itself w/o brackets is a constant pntr to char.

Explain this: char *string1 = "go bucks"

The individual chars in string1 make up a string literal( a string constant). String1 is a pntr to char, and it is a variable and can be made ot pnt to a diff string

Direct member access

The members if a structure are directly accessed with the dot operator. struct p; p.member

What is another thing the preprocessor does?

The preprocessor also replaces macros

What can you not put inside a struct directly or indirectly?

The same struct

Type of a const ptr

The type of a func pntr inclues the return type. numbers of parms and type of params in a certain order.

getchar() and putchar()

These functions are used fro inout and output for one character at a time.

Reserved identifiers

These identifiers reserve a word or identifier to have a particular meaning.

How are static arrays allocated

They are allocated either by the number of initalizers, or overridden by the size that given in the square brackets

Where is static storage variables located?

They are located on the heap

Where are automatic storage vairbales located ?

They are located on the stack

Enumerated data types

They are symbolic constants rather than literals: Declaration example: enum Container_Type {CUP,QUART, PINT}; //Cup will not have a value unless we assign it a value. //By default cup = 0, quart = 1, any other varaiblaes after would increase by 1. So pint = 2 decalration of the vauranle above: enum Container_Type variableName; /------------------------------------------------------ If there is only one declaration of variables of a particular enumerated type(no name) both statements may be cmbined enum {CUP,QUART,PINT}variableName; variableName is now an instance of the enum type and these variableas can now be assigne dthe CUP, QUART etc. no more variables of this type can be declared later bc no type name was given to it no pointers of this variable type can be declared BAD IDEA: vairableNamse = 231; int a = CUP; This is allowed: variableName = Cup;

What are preprocessor directives:

They are the # characters in the begining of a file. and are iued in a translation program called the preprocessor. They are not terminated with a semi colon

- c and -o, explain

They have nothing to do with makefiles, every thing to do with fcc. -c tells gcc to stop after compiling is done, and do NOT emit an executable -o tells gcc, heres the thing of the thing I want to produce.

Passing arguments fro the command line

They will be in read only memory Arguments can be asscessed by main by decalring 2 parameters fro main int main(int argc, char **argv){...} int main(int argc, char *argv[]){...}

What does this declare: int *findvalue(int value, int size, const int *array);

This is a function that takes in a int, and int, a int pnter, and returns a int pnter.

Dynamic allocation

This is runtime allocation, these functions must be used when you do not nkow while codeing how much storage will be needed.

What values are acceptable to free

Those that have been allocated a mempry space, once of thse pntrsgiven by malloc or calloc, realloc and only those values

A function pnts is not useful until it actually pnts to some func we wish to call

True

C does not have a string data type

True

C has no classes

True

C has no keywords such as true or false;

True

Compile word is overloaded

True

Function blocks can be legally empty and can consist of one or more blocks

True

There are no input or output defined in C itself, instead we use functions incorporated in stdio.h

True

In C it is also possible to access the value of a variable in memory using another variable(can also be a constant) which holds the 8 byte address of the first variable

True, we can do it w a pointer

Static and dynamic are overloaded terms

True: Examples: Dynamic memory Dynamic allocation Dyanmuc errir static error static memory static memory allocatuon static identifier class

What must we follow when assigning func pntrs

Tyoes must match, so we an actual funct and funct ptr, They both take a int, int pntr, and return an int so they are compatable types.

What is the type of a function

Type of a function carries parameter types in order and return types

B2U

Unsigned, simple binary

What is redirection of stdin, stdout, stderr

We can change the destination of each of these data streams from the unix/linux command lnes < redirects the input ( think labs, lab3 < x7.pbd) > redirectouts the output ( lab3 > my.x7.output) 2> redirects errors

How do we get around a simple function to swap or exchange two values with the following declaration: void swap(int x, int y)

We can get around this by passing pointers The code for this would be void swap(int *p, int *p1) { int temp = *p; *p = *p1; *p1 = temp; } main(){ int p; Int p1; void swap (&p,&p1) }

How can we get the size of an array

We can't get the size of an array, we need to pass it everywhere, no array function will tell you.

do we need to cast to and form void pnter

We do not need to cast when assigning to and from a void pointer, we generally use them when we need a anyomouys pntr

Address math is not the same as pntr math. why?

We don't have to scale when we do pnter math

Assignments are expressions in C, what does this mean

We know that an expression has a value, and that because assignment is an expression, than that means assignment must also have a value. This value for assignment is going to be the rightmost expression of the = . It has the lowest precedence other than comma. Embedded asisgnments are legal anywhere an expression is legal. EX: a = b =1 R-L associtivity other assignment operates like += -= *= %= work as well Using assignment operator = is legal anywhere it is legal to compare for equality ==, so no syntax error.

Short circuit evaluation

We see htis happen w java if(x &&y) if x is false, then the value of y doesnt matter It will just stop after x is false. U teach this shit the sw1 ppl

How does math arithmetic work vs pointer arithemetic , the details

When we do arithmetic with pointers (address math), the value added or subtracted is scaled by the compiler, using sizeof(type). Key* Adress math is with bytes This means if we add or subtract n from the address in a pnr varaibale ptr. the compiler will generate an instruction which adds or subtracts n*sizeof(*ptr) While for pntr arithemtic: We dont scale the integer, we add or subtrct by the size of the type or we get double scaling which leads to errors.

Checking bounds for pntrs

When we use pntrs to access dynamically allocated sotrage be sure that we do not use a pntr value that will attempt to access space outside the allocated storage. C does not have any bounds checking so we must keep tract of it explicity.

Expressions

Will be evaluated by the code which the compiler gernerates. This means that an expression has a value

are func pntrs variables

Yes they are so they can be assigned adresses of different functs

Will the compiler accept this and whats the value? What is this and why is it bad int a = 1 ++a--

Yes, but the behavior is undefined/ inexact. Bad bc we are not allowed to have more than one unsequenced side effect for 1 storage location A: a will be 2

int x is decalred outside of main, it is

a file scope name, that has external linkage Has a static storiage class and can not be changed. using static here will change the linkage

How does a pointer work

a location in memory is identified and referance with an 8byte adress when on a 64 bit address space like stdlinux values are stored in memory at a particular location which is usually unknown to a high level language programmer

What does a pointer store

a memory address and nothing else, true refereances store a lot more

Dereferance operatpr * can be used to

access data by indirection, when we use a pointer to access a value rather than accessing the value directly through a variable whivh hodlds that value, we access it indirectly through the pnt variable which holds the address of the value

How to make something unsigned

add 'u' to the modifier add unsigned keyword to variable type

& address opeerator gives the

address of a piece of data. this is always a constant, the constant represent sthe addressss determined by the compiler

What does scanf take

addresses

Where are all the elements of the array stored in memeory

all storesd in contiguous memeory

comma operator: How does this work: if( alt > 50,000) print("fffff"") else printf"hahaha")

alt = 65750 will print hahaha bc the comma makes it s.t alt is > 50 and 000, will return false.

Structures , data type

an agregate data type, that can store more than 1 indiividual piece of data at a time. C has 2 agregate data types, structs and arrays

precedene test: a = 1 b=3 c = 5 d = ++a *c + b++; Answer and what are the side effects here

answer 13 b is 3 bc postfix a is 2 c is 5 2*5+3 = 13 Side effects: b++ goes to 3 bc postfix ++a is rpefix so it is 2 = is the 3rd side effect

when should const keyword be used

anytime a pnter is passed as a parameter, if the function will not write to the variables peonted to by the pnter. It will aloowe the func to read values from the pntr but not affect he blaues in anyway.

Guarentted about argc and argv[]

argc is non-negitive, argv[argc] is a null pntr.

^

bitwise exclusive IR

<<

bitwise shift bits to the left

>>

bitwise shift bits to the right

~

bitwise, ones complement

storage scopeL 4 types but only covers 3

block file prototype

What type of symbol has no linkage

block scope

fall throughs are allowed when

breaks are ommited

C is compiled to _________ and not ___________

c is compiled to machne code, not byte code

Calling a func w a funct pnter with dereferanceing: call w params and return type call w no parms w return type calll w no parms or return type

call: i= (*fp)(arg1,arg2); no parm call: i = (*fp)(); if the func pnts a funct that has no parms or returns then its (*fp)()

Calling a func w a funct pnter without dereferanceing: call w params and return type call w no parms w return type calll w no parms or return type

call: i= fp(arg1,arg2); no parm call: i = fp(); if the func pnts a funct that has no parms or returns then its fp()

operators

can be classifed according to the number of operands which they take

Arrays of funct pntrs

can be used to replace na if, or switch statement when the functions all pass the same numner and type of params

fall through

case value 1: //code break; case value2; case value 3; break; fall through technique, cases value 2 and 3 all use the same case as val1

what does continue do

causes the loop to stop at its current iteration, do the adjustment(in the case for for loops) and begin to execute again from the top. it may only occur inside of any loop

A const pntr can not be

changed

single quotes is

char

Interger types

char short int long

List of reserved identifiers(30 of them). what does each do:

char short int long float double struct signed unsigned void const static enum extern typedef while for do if else switch case break return continue default goto auto register sizeof

Type casting heiarchy

char -> unsigned char -> short-> unsigned short -> int -> unsigned int -> long -> unsigned long -> long long -> unsigned long long -> float -> double -> long double

Order of sizes for integer types must hold

char < short< int < long

pointer arithmetic with strings

char string1[8] = "quick" char string2[5] = "dime" if(*(string1 + 0) == 'q') *(string2 + 0) ='t');

Sequence point operator

colon, semilcolon

>

comparison greater than

?:

conditional

Type of an array name

const pntr to the type it holds

Adress is a

constant

what is argv

contains pnts to the individual arguments as character strings no guarentee that the strings in argv are stored in contigous memory bc it is an array of pnts to the strings.

what is argc

contains the number of command line arguments

what does typedef do

creates a alias to an existing type

typedef

creates a new type, thats an alias to an existing type, a type def with a variable list makes all the vairbales in the variable list, a type name rather than a struct tag.

automatic storage classes Can be decalred where: When are variables created?| variables are initalized by what to what? What makes static varibales special

decalred within a block variabels are created just before exectuation of any code in the clock in which they are declared. variabke are initalized by our code ir they will contain garabage values parameters passed to function shave automatic storage class and there is no way to change this. Can have a register specifier

Storage class

determines 2 things: 1) determines the type of storage and lifetime of the storage associated with a variable 2) the variables initalization

Scope

determines the reigion of a program in which a variable can be accessed direcly by name and not pntr

What do pointers give us?

direct memoriy addess, store memory address and the adress is different memory is a dea of byte addressable bits

constants with decimal points

double

scanf dealing with size differences

double: use %lf l is for "long" since a double is longer than a float long double: use %Lf L uppercase because it is really long short: use %hd h is for "half" since a short is smaller than an int long : use %ld l is for "long" since long is longer than an int

static storage class runtime

during runtime: from the start of when the program laods and when the program terminates

what will be printed char string[] = {e,a,b,c,\0,u,h,c}

eabc

Arrays in C

elements of an array can be accessed using a pnter in C as well as by index 2 Tyeps of arrays: 1) stattically allocated The compiler generates code to allcoate the space for array elements at compile time . The space is allocated on the stack or head dependin on the declaration statemnt 2) Dynamically allcoated A c library finction is called to request space for the array elements at runtime, which is after the program begins running

boolean issues

everything is a boolean eben whem ot os not declarared as such

internal linkage is

file scope

file decalred outside any class is

filescope

Floating point types

float decimal long double

Order of sizes for floating point types

float < double < long double

Linkage

for a given name(identifier) determines whether the same name in a different scope refers to the same variable or function, or some different variable or function.

Macros

fragments of code, defined in the source file or ina header file. Macros hide code They are replaced with the code they are defined to represent Also, code in a source file is just text, so the macros are just chunks of text. EX: #define string 1 string2 string 1 can not contain any white space characters(tabs, spcae, new lines) but string 2 can

function protoype

function decalration or definition that includes 1) information about number of arguments 2) information about the types of arguments 3) What type od valueu the function returns

Explain this : int (*funcp)() int *func()

function pntr that takes in no parameters and returns an int. function that takes no parms and returns a int ptr.

compiling for c code depending on header files command

gcc -std=c99 -pedantic -Wformat -Wreturn-type -g -c $< -o $@

compiling makefile

gcc -std=c99 -pedantic -o file_name library1Name.c library 2Name.c

What does get char return and why

getChar returns an int and thisis because in band signaling When we fail to read something , we need to be able to differentiate from any of the characters we could have possible read in .. And all the possible characters we could read in, fill the all the possible characters we could use to indicate failure, as such, we desgined an int so that there are no unused characters that are designated for failure to raed. The returned int is the char we failed ot read Summary: integers used bc, certain txt file control values(EOF) dp not have one byte ascii encodings the integer values corrresponds to an given asci character. If it didnt return anything then we didnt fail to read anythign.

register keyword:

hardware registers

Where is the static storage class located in memory

heap

global variable stored int he

heap

stack

highest addresss autmatic storage class

how do we cahnge linakge for items that have linkage

if its external linkage ,key word static to change from external linakage to internal|

pointer arithmetic

if p = 1; if p points to the first integer inout example, then p+1 pnts to the 2nd integer and p+2 pnts to the thrid and p+n pnts to the (n+1)th Key: p points to the next int not byte

What happens when string is not null terminated

if the null character termination is not there, various library functions which can manipulate strings may not behave correctly, bc they will not be able to determine where the string ends. This will lead to a seg fault

When we make a call to calloc and malloc, what do we need to check?

if the return pntr is null

Minimum feild width,

if we dont specify the decimlas places to print, we can get more than the minimum feild with since it is the minimum not the max amt of places to be printed.

What are side effects

implied states of change

How do you code naive string copy? How would you do it by calling a function

in reg: char *string1 = "go bucks" int num = strlen(string1); char String2[inum]; while ((*string2++) = *string1++); in a function() main(){ funcCall(&string1, &string2); } function(char ** string1, char *string2[]){ while ((*string2++) = *string1++); }

scope of a automatic storage calss

inside a block scope

valid ways to assgine valeus to func ptr

int (*fp)(int a , int b); int sum(int x, int y); fp = sum; fp = &sum; //can access its elemets by: z = fp(i,j); these two ways are BOTH valid

decalre a func pntr array

int (*fpa[])(int a, int b) = {sum,diff,products} //to access its elements z = fpa[i](x,y)

How to declare a func pnter

int (*func_ptr)(); int (*fp)(int a , int b);

(*int_a)++

int gets incrememnted.

Decalration of static Arrays

int scores[6] = {1,2,3,4,5,6}; int scores = {1,2,3,4,5,6};

Assign adresses to a funct pntr array, int (*fpa[1])(int,int)

int sum(int a , int b); fp[0] = sum;

What type stores an enum

integer

storage Linakage 3 types

internal external none(no linkage)

What are constants with no decimal points

ints

A structure is

is a collection of values called members, but the memeber of a structure may be of different types. unlike elements of an array

automatic storage class runtime

is blockscope runtime, exists when initalized in the block and terminates once block finishes..

Difference between pointer to char and pointer to int

is how many memory locations are referenaced

storage class

is the type of memory in whcih the varables vaue is stored. Determines when the variable is created and destoryed and how long it retains it svalue. Determines whether the variable will be initalized byt he compiler or by code

What are Const

it is a promise on the other end about ehat you'll do but it does not change the type.

Regesiter is a request not a mandate. What does register do to stoage class

it modified automatic stroage.

what does goto do

jump statement, identifers must be unique ex: loop{ alsalda NAME: doedeosdoded code code doe code goto: NAME; code cod code}

printf dealing w sizes

long: use %ld only matters for numbers too big for an int long double %lf printf promotes float parameters to double so %f works for both float and double printf promotes smaller integer type paramters to int so %d works for int and smaller interger types

text

lowest storage class

When we create a size of arrary if characters as a string, we must:

make the size 1 greater then the actual string length.

Name of makefile can be

makefile or Makefile

-r

mandatory flag, supresses the implicit riles that make has. Use it to force make to build things only as you direct.

All variables have a

memory address in where they are stored

heap

midlevel/low adresses static storage class

% in math means

modulo

Header files

no code, only functon declarations or known as function protoypes,which tells the compiler information about a function. The information it tells hte compiler consists of return type and parameters. This isnformation is what the compiler needs tp be able to do error checking in compiling source code. DOES NOT CONTAIN CODE FOR THE FUNCTIONS, ONLY THE FUNCTION PROTOTYPES

The name of a func pntr is a _____

non null pntr

String is termined by

null and the ascii character '\0' the string ends where null is, regardless of how long the string is

Funtions

number of statemtns grouped into a single logical unit

pointer math:

p+1 points to the next int. The next int(pnt math) is sizeof(int) bytes away in memory(address math)

Can also access memory by doing subscripting which is

p[2];

When doing pass by reference, the 8 btye referance is still

passed by value

C passes arguments to functions by what and when does it happen

passes by value and in all cases Ex: int test(int a , int b); Ensure that the values passes to the function can not be chanfed in the calling program by the called function

When you increment the pntr, the stored address changes by the size of theing it pnts to so:

pntr to a long is 8 bytes. When I incremented a pnter to long by 1, it pnts to the address 8 bytes later in memory, the stored adddress got increased by 8

How can we access elements beyond the first element in p = malloc(6* sizeof(int))

pointer arithemetic

What does format string come in as

pointer to char

double quotes is type

pointer to char

The type of a pointer is :

pointer to the type of data to which it points

3 parts of memory are made accessable by what

pointers

What operations have side affects

post++, ++pre, = assingment

What does printf take

printf takes values

How would u redirect stdout and stderr to the same file file program , fileB and c,. same file is c

program > fileB 2> &c

what does register do

register is faster to access than memory, so all the variables we use constantly/alot in our program can be assigned to the register.

Calloc

returns a pntr ot a void, which pnts to hte address of the first byte of the allocated mmemory space on the heap. The memory returned by calloc is initalized to 0. so if you do not plan to initalize the values before using them, use calloc and not malloc allocat 6 ints int *p; p = calloc(6,sizeof(int));

Malloc

returns a pntr to void, which pnts to the address of the first byte of the allocated memory space on the heap. Memory returned by malloc is uninitialized(contains garabage values) so be sure to initialze it b4 using it . requesting enough bytes for 6 integers int *p p = malloc(6*sizeof(int));

what is sizeof

returns the size of an object

prog1 2>> errorfile

runs prog1 and puts any error into the error file.

prog1 >> outputfile

runs program prog1 and write output to outputfile

Memory is a

sea of byte addressable bits

Errors that occur at run time are known as

semantic errors

what does static on block scope do?

since blockscope doesn't have any linakge, static keyword would change the automatic storage class to static

What do types tell us

size and interpretation

size of char

smallest adressable unit, 8 bits, 1 byte guarenteed

Where is the automatic storage class located in memeory?

stack

3 parts of memory

stack heap text

Storage class types 4 types, tecnically 3

static automatic register external(linakge)

How do we change block scope variable from stack to heap

static key word

String functions in string.h

strcat() appends a string strchr() finds first occurance of a given character strcmp() compares two strings strcmpi() compares two strings non-case sensitive strcpy() copies one string to another strlen() finds length of string strwr() converts string to lower case strnset() sets characterts ot a string to a given character strrev reverses a string strspn finds first subbstring from given character set in string strstr returns a pntr to the first occurance of s2 in string s1 str upr converst string to uppercase

Difference between char arrays and strings

strings are null terminared

left side of dot

struct

right side of dot and arrow

struct member

left side of a arrow

struct pntr

Format for a struct

struct tag { member list} varibale list; tag or variable list are optional but one of the is requried. if tag is ommited, only the variables declared in the variable list can access the memebers, no other variabels can ebe decalred of this type struct. A tag feild is req if we want to use calloc or malloc.

Distinction about strucutres

structures are not an array of ts members, unlike an array name, the name of a strucutre variable is not replaced with a pointer when it is used in an expression

Switch

switch<variable> //variable must be an int type case value1: //value 1 is a constant known at compile time code to execute if <variable> == value1; break; //optional break, but good ideas to. case value 2....

int i = 5; char *y = (char*)(&i)

takes the adress of int i, which is 4 bytes, since char is 1 byte, it says pull up 1 byte out of the 4 bytes that make up the int. And that 1 byte will be the char value.

$@

target of the current rule

makefile rules

target: dependiences [tab] system command system command: gcc -g -o $@ $^ -libraries

Malloc and calloc returns a void pntr that ponts to

tbhe address of the first byte of the allocated memeory space ont he heap. If the allocation fails, they return a null pntr.

What does sequence point operator do in terms of side effects

tells when the side effect will settle

Explain what all these lines do:

the command "make" will make all the targets in all, and then proceed to build the target versions of the dependences of each target in all.

$^

the dependicnes of the current rule

$<

the first dependency of the current rule

switch cases chooses

the first value that it matches

Integer divide

the fractional/decimal part gets truncated

what is true abt this statment: int returnMax(int size, const *array); inf(*fp)(int, int*) f = returnMax or fp = &returnMax Why

the function returnMax must be declared before assigning its adress to the funct pntr. But it does not need to be defined this is bc the compiler can do type checking for compatibility

static keyword

the heap

what does auto do

the runtime stack

The value of a assignment expression is

the value assigned

$*

then stem with which the pattern of the current rule is matched

Semantic errors

these don't make a program invlaid/ not compile. Bc this happens at run time, we know that the program can be built and executed, hence the program would be valid. Ex: divison by zero Compiler will not discover a error but when the program runs. the excepetion will be generated and the operationf sustem will terminate the program

Static storage classes Can be decalred where: When are variables created?| variables are initalized by what to what? What makes static varibales special

they are the default for any variables decalred outside any blocks variabkes are created before the origram begins to run and last till the program terminates variables are initailzed by default by the laoder and initalized to a 0 value for their decalred type they retain the last value they were assigned to until the program completes

Why do we use void pntrs?

to overcome the issue of assigning spererate values to different data types in the program, since vp and hlad any address

We dont usually pass adresses to printf except strings

true

pointers are variables so they can be used w/o dereferanceing

true

scope drives linakge and linkage changes scope

true.

what does the pointer itself tell you

type and size, pointer itseld carries a type and the tyoe of pointer tells you the size od the thing they pnt to

What is a decalration

type information only, no values. for a variable, it tells the compiler the return type and the number and types of its parammeters. Parameter names are optional For a variable: a variable can only be declared once in a given block in a C program For a function: a function can be declared multiple times in a C program as along as all of the decalrations are consistent. aka identical with respect to tyoes.

void do_thing (int (*fp(int, int), int x , int y); write this using type def

typedef int (*yo)(int a, int b); void do_thing (yo fp, int x , int y); //pass a func pntr do_thing(sum,i,j)

How do we access structure members

use -> or . Structures memeebers are given names(identifiers) and are accesed by those names.

comma operator

used to link related expressions together. Evaluated from left to right The value of the rightmost expression is the value of the while combined expression it forces a sequence point, all side effects are settled paraentheses are necessary. if there are no paratenthesis around an expression with commas, the commas are sperators and not the comma operator. ex: i = a,b,c //stores a into i, comma is a sperator i =(a,b,c) //stores c into i, these commas are comma operators Better to not use a comma operator unless we want to use this as a boolean, for example to control a loop or an if-else conditional

Pointer is a

variable or a constant that contains the address of another variable

Whats the relationship between struct variable lists and space

varibales in the varibale list decalres space.

free() returns what and what must its parameter point to

void and its parameter must pnt to the 1st bypes of the accloacted memory space.

function pntr param for another func

void do_thing (int (*fp(int, int), int x , int y);

Every pntr points to a specific data type execept

void pntrs

If we put paramters at the end of a func pnter, what are we doing

we are effectivly dereferancing it by making the call

Can we have pntr to structs inside a struct

we have to use the bames to get hrte sturctures, pointer is a different type than the sturct istedl therefore it is allwoded.

pass by referance

we pass a pointer to the parameter This allowes the function to alter the variable which is used to pass the parameter's value in the calling environement.

Passing pntrs: how to change a variable in a calling function What if we have ***p as the variable I want to change

we pass the argemnt to the function as &p The incoming parameter of the func will be ****p we change the value of p by doing *p

Passing pntrs: how to change a variable in a calling function What if I have int *p as the variale i want to change

we pass the argemnt to the function as &p The incoming parameter of the func will be **p we change the value of p by doing *p

Passing pntrs: how to change a variable in a calling function What if I have int p as the variale i want to change

we pass the argemnt to the function as &p The incoming parameter of the func will be *p we change the value of p by doing *p

Fomatted based I/O

zero or more characters witha requirement to specify the format of the input or output scanf printf these use format strings to specify interpretation % before string


Set pelajaran terkait

Digital Literacy Unit 1: Lesson 2: True or False

View Set

Modern Database Management - Final Study

View Set

History 101 FINAL EXAM cummulative

View Set

Types Of Individual Life Insurance

View Set