AP Notes, Outlines, Study Guides, Vocabulary, Practice Exams and more!

C programming Flashcards

C programming conceps

Terms : Hide Images
1108503812#preprocessor directive0
1108503813#include< >replaces the directive with the content of thee file whose name is listed in the directive1
1108503814stdio.hstandard input output header file2
1108503815puts(" ");writes something on the screen3
1108503816arguments or parametersthings put inside a function4
1108503817prototypelabel affixed to a function and announcing how you can use that function in your program. result, name, parameters. Ex. int main(void)5
1108503818bodythe interior of the function, tells what the function is intended to.6
1108503819returnstatement that causes the end of the function execution7
1108503820typecharacteristic of a number which determines its kind, range and application. attribute that uniquely defines which values can be stored inside the variable.8
1108503821integer type - intenteros9
1108503822floating point type - floatcon decimales. We can say that the point makes a float. 4 is an int. 4.0 is a float.10
1108503823octal valueinteger number is preceded by the 0 digit, 0123 = 83 decimal11
1108503824hexadecimal numbershould be preceded by the prefix written as 0X, 0x123 = 291 decimal12
1108503825variablesspecial "containers", with a name, type, and value13
1108503826variable's name1.-must be composed of upper-case or lower-case Latin letters, digits and the character _ (underscore); 2.- must begin with a letter 3.-the underline character is a letter (strange but true) 4.-upper- and lower-case letters are treated as different Note: same restrictions apply to the function names14
1108503827declarationThe variable comes into existence as a result of a declaration. A declaration is a syntactic structure that binds a name provided by the programmer with a specific type offered by the "C" language. Ex. int Counter; Ex. int variable1, account_balance, invoices;15
1108503828assignment operator= , give the value to the declared variable. Ex. Counter = 1;16
1108503829x = x + 1;Take the current value of the variable x, add 1 to it and store the result in the variable x17
1108503830keywords or reserved keywordsThe meaning of the reserved word is predefined and mustn't be changed in any way. Ex. case, break, continue, default, do, goto, extern, short, struct....18
1108503831commentsThe compiler ignores it. Good and responsible developers describe each function; in particular, explaining the role of the parameters, the value the function returns as a result and what the function actually does. Ex. /** Esto es un comentario **/19
1108503832scientific notation in "C" language300000000 is the same as 3E8 The letter E (you can also use the lower case letter e - it comes from the word exponent) is a concise record of the phrase "times ten to the power of". Note: the exponent (the value put after the "E") has to be an integer. the base (the value put in front of the "E") may be an integer. small values like 6.62607 x 10-34 are represented in C as 6.62607E-3420
1108503833division operator/ (slash)21
1108503834type automatic castingint i; float f; i = 100; f = i ; //f would be 100.0, no loss of accuracy int i; float f; f = 100.25; i = f; //i would be 100, loss in accuracy22
1156288282specifier% joined together with some other character(s) %d (as in decimal) value of type int %x(as in hexadecimal) value of type int %o (as in octal) value of type int %c(as in char) value of type int or char %f(as in float) value of type float %%(as in itself) presents the percent sign23
1156288283formatthe first, and only mandatory argument of printf. printf("This is the format");24
1184770106indexThe value put inside the brackets which selects one element of the vector is called an index. Any expression could be an index. numbers[1];25
1184770107indexingThe operation of selecting and element from an array26
1184770108sizeofThe operator we want to introduce now is distinguished by its appearance. The new operator looks like a variable. Don't be misled: this is a unary prefix operator and with the highest possible priority. Provides information on how many bytes of memory its argument occupies (or may occupy). Expects that its argument is a literal or a variable or an expression enclosed in parentheses or the type name (this is the only "C" operator which allows its argument to be a type). You may not use parentheses when the argument is a literal or a value but you must use them when the argument is a type. The sizeof is not only an operator - it is also a keyword.27
1184770109pointers and arraysif there is a name of an array without the indices, it is always a synonym of the pointer pointing to the first element of the array. Arr == &Arr[0]28
1184770110Pointers' arithmetic/ adding an integer value to a pointer giving a pointer (ptr + int → ptr) / subtracting an integer value from a pointer giving a pointer (ptr - int → ptr) / subtracting a pointer from a pointer giving an integer (ptr - ptr → int) / comparison of the two pointers for equality or inequality (such comparison gives a value of type int representing true or false) (ptr == ptr → int; ptr != ptr → int29
1184770111pointer additionAdding an integer value to a pointer giving a pointer (ptr + int → ptr) ptr2 = ptr2 + 1; ptr2++; The interpretation of this operation is as follows: it has taken into account what type is pointed to by the pointer - in our example it is int. it is determined how many bytes of memory the type occupies (the sizeof operator is implicitly used for that purpose) - in our case it will be sizeof (int). the value we want to add to the pointer is multiplied by the given size; the address which is stored in the pointer is increased by the resulting product; In effect, the pointer moves itself to the next int value in the memory.30
1184770112pointer substractionSubtracting a pointer from a pointer giving an integer (ptr - ptr → int) i = ptr2 - ptr1; The final result tells us how many variables of a given type (i.e. int) fits between the addresses stored in the pointers. How is it calculated? taken into account: the type to which the pointers point (int); it means that it is required for both pointers to point to the same type; the compiler will check it the addresses stored in the pointers are subtracted the result of the subtraction is divided by the size of the type pointed to by the pointers31
1184770113%dTo print a pointer printf("Direccion del primer elemento del Array: %p\n", ptr1);32
1184770114'/0'empty character or null, is the terminating tag.33
1184770115function prototypeThe prototype consists of: /return type (the type of the result) /name of the function /list of its parameters as well as their types int puts(char *s);34
1184770116return valueit is a non-negative number if everything goes well and -1 if the ffunction is not able to meet our demands due to any reason.35
1184770117value and address of a variable-The value of the variable is what the variable stores; -The address of the variable is information about where this variable is placed (where it lives)36
1184770118pointerare used to store information about the location (address) of any other data. We can say that pointers are like signposts.37
1184770119null pointerYou can assign the zero to the pointer variable. Such assignment does not raise any compiler's doubts. Such pointer does not point to anything. p = 0; but its better to use the macro NULL, p = NULL; which is defined in stdio.h or stddef.h. don't forget that dereferencing NULL pointers is strictly forbidden and lead to the so-called runtime error which stops your program's execution at once.38
1184770120reference operator& How to assign a value to the pointer variable? p = &i;39
1184770121dereferencer* f you put an asterisk in front of a pointer you will get a value which is stored at the location pointed to by the pointer. *ptr40
1184770122*ptr = 4;you won't change the pointer value. You will change the value pointed to by the pointer instead.41
1193868114ptrtab[2][1]*(*(ptrtab + r) + c)42
1193875227SemanticsMeaning43
1193875228SyntaxSymbolic representation44
1193926501argc and argvargument counter and argument values int main(int argc, char *argv[]) argc (as in argument counter): contains the number of arguments passed on to the program plus one; that means that a program run without any arguments will have the argc parameter value equal to 1 argv (as in argument values): an array of pointers to strings containing the arguments supplied to the program; they are stored in the following way: argv[0] contains the name of the running program argv[1] contains the string passed to the program as the first argument argv[n] contains the string passed to the program as the n-th argument45
1193926502recursionthe function invokes itself. int factorial(int n) { if(n == 1) return 1; else return n * factorial(n - 1); }46
1193926503?: operatorexpression1 ? expression2 : expression 3 requires three arguments. This operator works as follows: -calculates the value of the expression1 -if the calculated value is non-zero, the operator returns the value of expression2 neglecting completely expression3 -if the value calculated in step 1 is zero the operator returns the value of expression3 omitting expression2. i = i > 0 ? 1 : 0; same as if(i > 0) i = 1; else i = 047
1193926504false and truefalse = 0 true = any value that is not 048
1193926505extern(as external). This is a keyword often called an attribute which can be used along with the declarations of functions and variables. Its presence indicates that the function/variable described in this declaration is defined in a different source file. extern int factorial(int n);49
1193926506definition and declaration of a functionint CountSheep(void); /* declaration */ int CountSheep(void) { /* definition */ return ++SheepCounter; } declaration of a function is the part of the code which contains all three key pieces of information (name, parameters, type) but doesn't contain the body of the function. The declaration of the function is often called a function prototype. A definition of a function is a part of the code containing its full implementation (including the body).50
1199148538canonical file namethe name which uniquely defines the location of the file regardless of its level in a directory tree. Windows: C:\directory\file (not case sensitive) Linux: /directory/files (case sensitive) char *name = "\\dir\\file"; In windows we have to use double '\' cuz '\' is the escape character.51
1199148539streamabstract entity to communicate with the files. Operations performed with the abstract stream reflect the activities relating to the physical file. To connect (bind) the stream with the file, it is necessary to perform an explicit operation. The operation of connecting the stream with a file is called opening the file while the disconnection of this link is named closing the file. Hence the conclusion that the very first operation performed on the stream is always open and the last one is close.52
1199148540open modeThe opening of the stream is associated not only with the file but should also declare the manner in which the stream will be processed. This declaration is called an open mode. there are two basic operations performed on the stream: read from the stream: portions of data are retrieved from the file and placed in a memory area managed by the program (e.g. a variable) write to the stream: portions of data from memory (e.g. a variable) are transferred to a file53
1199148541open a streamThere are three basic modes used to open the stream: -read mode: a stream opened in this mode allows the reading of operations only; trying to write to the stream will cause a runtime error -write mode: a stream opened in this mode allows the writing of operations only; attempting to read the stream will cause a runtime error; -update mode: a stream opened in this mode allows both the writing and the reading.54
1199148542current file positionThe stream behaves almost like a tape recorder. When you read something from a stream, a virtual head moves over the stream according to a number of bytes transferred from the stream. When we write something to the stream, the same head moves along the stream recording the data from the memory. Whenever we talk about reading from and writing to the stream, please, have the imagination in the forefront of your mind. The programming books refer to this mechanism as a current file position and we will also use this term.55
1199148543FILE typethe type named FILE is used to represent streams in the program. From the programmer's perspective the way in which the FILE is declared is completely irrelevant. The programmer will never use the data directly but only through library functions. The developer should never be tempted to manipulate data of this type. A variable of type FILE is created when you open the file and annihilated at the time of closing. Between these two events you can use this data to specify what operations should be performed on a particular stream. However, due to the definitions of functions which operate on this data the program doesn't use variables of type FILE but pointers to them. The FILE type is defined inside the stdio.h header file. Any program using a stream needs to include this file.56
1199148544text and binary streamsneed to be specified. text file: Structured in lines, that is, they contain typographical characters (letters, digits, punctuations, etc) arranged in rows (lines), as seen with the naked eye when you look at the content of such a file in the editor. Such a file is written (or read) mostly a character by character or line by line. binary file: Sequence of bytes of any value. This sequence can be, for example, an executable program, an image, an audio or a video clip, a database file, etc. Because these files don't contain lines, the reads and the writes relate to portions of data of any size. Hence the data is read/written byte by byte or block by block where the size of a block usually ranges from 1 to the arbitrary chosen value.57
1199148545fopen();FILE *fopen(char *file, char *openmode); the name of the function comes from the words "file open" if the opening is successful the function returns a pointer to a newly created variable of type FILE; otherwise it returns NULL, which can be easily used to validate the invocation the first parameter of the function specifies the name of the file name to be associated with the stream; the name must be written according to conventions applicable in a particular operating system the second parameter specifies the open mode used for the stream; it is described by the sequence of characters and each of them has its special meaning (more details soon) the opening must be the very first operation performed on the stream (there is a triple exception of that rule - more details soon)58
1199148546open modes"r" read the file associated with the stream must exist and has to be readable, otherwise the fopen function fails "w" write the file associated with the stream doesn't need to exist; if it doesn't exist it will be created; if it exists it will be truncated to the length of zero (erased); if the creation isn't possible (e.g. due to system permissions) the fopen function fails "a" append the file associated with the stream doesn't need to exist; if it doesn't exist it will be created; if it does exist the virtual recording head will be set at the end of the file (the previous content of the file remains untouched) "r+" read and update -the file associated with the stream must exist and has to be writeable, otherwise the fopen function fails -both read and write operations are allowed for the stream "w+" write and update -the file associated with the stream doesn't need to exist; if it doesn't exist it will be created; the previous content of the file remains untouched -both read and write operations are allowed for the stream If there is the letter b at the end of the mode string it means that the stream is to be opened in the binary mode. This is the default behaviour assumed when no binary/text mode specifier was used. If the mode string ends with the letter t the stream is opened in the text mode. rt rb wt wb at ab r+t r+b w+ w+b59
1199148547stdin stdout stderrFILE *stdin, *stdout, *stderr; There are three well-defined exceptions to the rule. When our program starts the three streams are already opened and don't require any extra preparations. stdin (as in standard input) the stdin stream is normally associated with the keyboard, pre-open for reading and regarded as the primary data source for the running of programs; the well-known scanf function reads the data from stdin by default stdout (as in standard output) the stdout stream is normally associated with the screen, pre-open for writing, regarded as a primary target for outputting data by the running of the program the well-known printf function outputs the data to stdout stream stderr (as in standard error output) the stderr stream is normally associated with the screen, pre-open for writing, regarded as the primary place where the running program should send information on the errors encountered during its work The separation of stdout (useful results produced by the program) from the stderr (error messages, undeniably useful but providing no results) gives the possibility of redirecting these two types of information to different targets.60
1199215908fclose()int fclose(FILE *stream); The last operation performed on a stream (this doesn't include the stdin, stdout, and stderr streams which don't require it) should be the closing. -the name of the function derives from words file close -the function expects exactly one parameter: a pointer to a variable of type FILE representing the stream to be closed; the stream should be opened -the function returns 0 on success or a value identified by the symbol EOF otherwis61
1199215909EOFthe EOF symbol is declared in the stdio.h file and represents the value equal to -1; its name comes from the term End Of File.62
1199215910errno variableextern int errno; The definition of the errno variable (the name comes from the phrase "error number") is located in the errno.h header file. By definition, execution of any function operating on stream sets the errno variable with the error code identifying the reason of failure. The value of the errno variable can be compared with one of the predefined symbolic constants (also defined in the errno.h file) which provide a basis for determining the actual reason of the error. EACCES: Permission denied EBADF: Bad file number EEXIST: File exists EFBIG: File too large EISDIR: Is a directory EMFILE: Too many open files ENOENT: No such file or directory ENOSPC: No space left on device FILE *file = fopen("c:\\file.txt","rt"); if(file == NULL) { switch(errno) { case ENOENT: printf("The file doesn't exist\n"); break; case EMFILE: printf("You've opened too many files\n"); break; default: printf("The error number is %d\n",errno); } }63
1199215911strerror()char *strerror(int errnum); function that can dramatically simplify error handling code. Its role is simple: you give an error number and get a pointer to a text describing the meaning of the error. Now we can simplify our code in the following way: FILE *file = fopen("c:\\file.txt","rt"); if(file == NULL) printf("File could not be opened: %s\n",strerror(errno));64
1199215912fgetc()int fgetc(FILE *stream); reading one character from the stream -the function name derives from the words file get character -the function expects one parameter of type FILE *; the parameter must be a pointer to a stream opened for reading or updating -the function attempts to read one character (byte) from the stream identified by the parameter; if it is possible the function returns the code of the retrieved character as its result: it will be a number out of the 0..255 range; the current file position moves one byte towards the end of the file -if the attempt fails (e.g. because the current file position is already located after the last character in the file), fgetc returns the value of EOF (-1) and the file position is not changed -the function might be used for reading characters from a text file as well as reading bytes from a binary file. There is an additional function with the following prototype: int getchar(void); and causes the same effects as the following invocation: fgetc(stdin); The former function is used for reading a single character from the stdin stream.65
1199215913fgets()char *fgets(char *str, int maxsize, FILE *stream); reading one character from the stream -the function name derives from the words file get string -the function expects the following three parameters: -str: a pointer to a string in which fgets will store one line taken from the stream -maxsize: the maximum number of characters that can be safely stored inside the str including the empty character terminating the string and the \n character got from the stream -stream: a pointer to the stream opened for reading or updating -the function attempts to read one line of text from the stream; if it succeeds the function stores at most maxsize characters in the string pointed to by str; if the file contains lines of greater length, they will be read part by part; -if the reading was successful, the function returns the value of the str parameter, the current position of the file is moved to the place after the last retrieved character -otherwise the function returns NULL as a result and the current file position is not changed The function is definitely not to be used for reading binary files.66
1199215914MAXINTsymbolic constant representing the maximum value of type int.67
1199215915fread()int fread(void *mem, int size, int count, FILE *stream); reading bytes from the stream -the function name derives from the words file read -function expects the following four parameters: -mem: a pointer to a memory in which fread will store one the portion of bytes read from the stream -size: the size (in bytes) of the portion to be read -count: the number of portions to be read -stream: a pointer to the stream opened for reading or updating the function attempts to read size * count bytes from the stream; if it succeeds the function stores the read bytes in the memory pointed to by mem; -the function returns the number of the successfully read portions; it may, but does not have to, be equal to the count value; a value of 0 says that the function was unable to read any portion; the current position of the file is moved to the place after the last read byte -The function is ideal for reading binary files because you can use it to read a specific number of bytes. Suppose that we want to retrieve the value from the input stream and store the bytes in the number variable. The following declarations apply: int number; FILE *input; The reading could be performed in two equivalent ways: fread(&number, sizeof(int), 1, input);68
1199215916buffercommon name for memory used temporarily to store output or input data69
1199215917fscanf()int fscanf(FILE *stream, char *format, ... ); formatted reading from the stream The functions we've met so far read the data from the file and send it into the memory virtually unchanged. However, this is a function that is able to read a string representing any value and convert it directly to the internal representation. This function expects the following parameters: -stream: a pointer to the stream opened for reading or updating; -format: a pointer to a string describing what data should be read from the stream; detailed descriptions of the format can be found in Chapter 2 of our course; - ... : a list of pointers to variables to be assigned with values read from the data stream The function returns the number of values correctly read from the stream. This number may be less than the number of pointers in the ... list and can be even equal to zero if the stream doesn't contain any characters that can be interpreted as values specified by the format. scanf if is a special case of fscanf. scanf("%d", &number); // is the same as fscanf(stdin, "%d", &number);70
1199215918fputc()int fputc(int chr, FILE *stream); writing one character to the stream -the function name derives from words file put character -the function expects two parameters: -chr: a code of the character (or the character itself) to be output to the stream -stream: a pointer to the stream opened for writing or updating if the function succeeds it returns the chr character code as its result; it will always be a number between 0 and 255; the current file position moves one byte towards the end of the file; -in the event of failure (e.g. because of insufficient disk space) fputc returns the value of EOF (-1) and the file position is not changed -this function can be used for writing characters to a text file or bytes to a binary file int putchar (int chr); //same as fputc(chr, stdout);71
1199237503fputs()int fputs(char *string, FILE *stream); writing a string to the stream -the function name derives from the words file put string the function expects two parameters: -string: a pointer to the string to be written to the stream; note: the function will implicitly add a \n character at the end of the string; -stream: a pointer to the stream opened for writing or updating the function attempts to write the content of the string to the stream -if the function is successful, it returns a non-negative number and the current position of the file is moved towards the end of the file -in the event of an error the function returns EOF as a result; the current file position is unchanged; -the function is definitely not intended to write data to binary files as it is not possible to write a byte of value 0 - can you explain why? Here is a function (you already know it) with the following prototype: int puts(char *string); which is an equivalent of: fputs(string, stdout);72
1199237504fwrite()int fwrite(void *mem, int size, int count, FILE *stream); writing bytes to the stream -the function name derives from the words file write -the function expects four parameters: -mem: a pointer to the memory area to be written to the stream -size: the size (in bytes) of one memory portion being written -count: the number of portions intended to be written -stream: a pointer to the stream opened for writing or updating. -the function attempts to write (size * count) bytes from the mem to the stream -the function returns the number of successfully (actually) written portions and the current position of the file is moved towards the end of the file; the result may differ from count value due to some errors preventing the successful writing -the function is ideal for writing to binary files, but you can use it to create text files too if you provide appropriate handling of the endline characters73
1199237505fprintf()int fprintf(FILE *stream, char *format, ...); formatted writing to the stream -The function expects the following parameters: -stream: a pointer to the stream opened for writing or updating -format: a pointer to a string describing data to be written to the stream; - ...: a list of expressions whose values will be converted into human-readable form and written to the stream -the function returns the number of characters (not values, as opposed to the fscanf function) correctly written to the stream. Let's say that this function enables us to send error messages directly to the stderr stream, which is, as you already know, encouraged and welcome. printf("%d", number); //same as fprintf(stdout, "%d", number);74
1201474062ftell()long ftell(FILE *stream) getting the stream's position specifies what the current position of the file is. The position is counted from the beginning of the file and it is assumed that when the file is opened in a mode different than "a" it is equal to zero (i.e. it points to a position placed before the first byte of the file). -the function name derives from words file tell -the function expects one parameter which is a pointer to the opened stream -the function returns the distance (in bytes) counted from the beginning of the file to the current file position; thus, the first byte of the file is located at position zero -in error the function returns EOF (-1) as the result -the function affects neither the position of the file nor its content75
1201474063fseek()int fseek(FILE *stream, long offset, int whence); setting the stream's position The fseek function allows us to set the current position of the file. If the setting is successful the next read/write operation will affect that very position. -the function name is derived from the words file seek -the function expects the following three parameters: -stream: a pointer to an opened stream -offset: a value describing the target position (may be negative) -hence: a value indicating a reference point, i.e. saying how the new position is to be calculated; usually the role of this parameter is played by one of three symbolic constants: -SEEK_SET: the offset parameter specifies the position calculated from the beginning of the file; -SEEK_CUR: the offset parameter specifies the position calculated from the current file position -SEEK_END: the offset parameter specified the position calculated from the end of the file -in the event of an error the function returns EOF (-1), otherwise, the return value is 0 -the function obviously affects the current position of the file. Please, be aware that not all of the files allow for the setting of the current position. The most obvious examples are the files associated with the stdin, stdout and stderr streams. Setting the position is impossible for streams associated with devices which operate sequentially, like a keyboard or a printer.76
1201474065random access and sequential accesssequential access: data is written/read in a consecutive order. random access: data is not necessarily written/read in a consecutive order.77
1201568494rewind();void rewind(FILE *stream); As in the old magnetic tape storage devices we are able to rewind the 'tape' to the beginning to be re-read or re-written. //Same as fseek(stream, 0, SEEK_SET); except the fact that rewind does not return any value and doesn't set the errno variable.78
1201568495feof(FILE *stream);int feof(FILE *stream); end of the file (EOF) state occurs when there is nothing more to read in the file. We used to discover EOF state somehow indirectly: we just tried to read the stream and when it failed we assumed that the EOF had already occurred. In other words, we acted somewhat forcefully, not even asking if the read operation was feasible. It can be done in a more careful way: we can first ask if there is something to read and then read it. This function returns a non-zero value if the stream is in the EOF state, otherwise, the return value is 0. while(!feof (input)) { fgets (line, sizeof(line), input)); fputs (line, output); }79

Need Help?

We hope your visit has been a productive one. If you're having any problems, or would like to give some feedback, we'd love to hear from you.

For general help, questions, and suggestions, try our dedicated support forums.

If you need to contact the Course-Notes.Org web experience team, please use our contact form.

Need Notes?

While we strive to provide the most comprehensive notes for as many high school textbooks as possible, there are certainly going to be some that we miss. Drop us a note and let us know which textbooks you need. Be sure to include which edition of the textbook you are using! If we see enough demand, we'll do whatever we can to get those notes up on the site for you!