CSE 124 Discussion (10/3) C/C++ Basics
Topics - main() function - Compiling with gcc/makefile - Primitives - Structs/Enums - Function calls/loops - C++ Classes/stdtl - Pointers/Arrays - Memory allocation/freeing - C vs C++ Strings - File I/O - GDB
Overview C was developed by Dennis Richie in AT&T Bell Labs -1972 C is a structured programming language. C enables modularity by breaking large file into smaller modules/blocks.
main() function main() is the entry point of every C program. Generally, the main() function will set up the environment and then call other functions/libraries that do the actual work. Every C/C++ program must have a main() function. The main() function supplies command line arguments via the argc and argv variables.
Compiling with gcc/makefile Makefiles are a simple way to organize code compilation. Individual C files can be compiled and executed as follows: gcc sample.c -o sample./sample For a group of files and headers you can compile the project by using a Makefile, and running the make command in your terminal. //Show code
Primitives Primitive types are the most basic types in C/C++. int, short, char, float, long, byte, are all primitive types. Pointers are a type that points to another type. The void type is special- it represents nothing.
Structs/Enums A struct in C is a collection of different data types called members. typedef struct Books { char title[50]; char author[50]; enum genre book_genre; int book_id; } book; Enums are explicitly named constants that can be used in other code. enum genre { Horror, //0 Fiction, //1 Drama //2 }; enum genre my_book_genre = Horror;
Function calls/loops 1 #include<stdio.h> 2 // function prototype, also called function declaration 3 float square ( float x ); 4 // main function, program starts from here 5 6 int main( ) 7 { 8 float m, n ; 9 printf ( "\nenter some number for finding square \n"); 10 scanf ( "%f", &m ) ; 11 // function call 12 n = square ( m ) ; 13 printf ( "\nsquare of the given number %f is %f",m,n ); 14 } 15 16 float square ( float x ) // function definition 17 { 18 float p ; 19 p = x * x ; 20 return ( p ) ; 21 } // Program to calculate the sum of first n natural numbers // Positive integers 1,2,3...n are known as natural numbers #include <stdio.h> int main() { int num, count, sum = 0; printf("enter a positive integer: "); scanf("%d", &num); // for loop terminates when n is less than count for(count = 1; count <= num; ++count) { sum += count; } } printf("sum = %d", sum); return 0; // Program to find factorial of a number // For a positive integer n, factorial = 1*2*3...n #include <stdio.h> int main() { int number; long long factorial; printf("enter an integer: "); scanf("%d",&number); factorial = 1; // loop terminates when number is less than or equal to 0 while (number > 0) { factorial *= number; // factorial = factorial*number; --number; } printf("factorial= %lld", factorial); return 0; }
C++ classes/stdtl The C++ standard library includes many classes that can be useful. This includes strings, thread objects, and more! You re allowed to use any classes in the standard C++ library, provided it doesn t violate other project restrictions. http://www.cplusplus.com/reference/
Pointers In C/C++, everything has a memory address. A memory address of an object is called a pointer to that object. Pointer types are denoted with the * character. You can get the pointer of any object by using the & character in front of it, and the data at a pointer by using the * character: int some_val = 5; int* pointer_to_some_val = &val; int the_value_of_some_val = *pointer_to_some_val;
Arrays In C/C++, an arrays and pointers are interchangable. An array is really just a pointer to a bunch of objects: int my_ints[5]; // typeof(my_ints) == (int*) int* pointer_to_elem = &my_ints[2]; *(pointer_to_elem + 1) == my_ints[3] == *(my_ints + 3); // true my_ints + 2 == pointer_to_elem // also true
Memory allocation/freeing In C, memory can be allocated in two ways: 1. Static Memory: Here you need to define the memory size on declaration. This is allocated on the program stack. 2. Dynamic Memory: Here you can allocate/reallocate/free memory during runtime. This is allocated on the program heap.
Stack vs Heap In C/C++, memory can be allocated in two places: the stack and the heap. The stack contains all of the program code and variables that are defined in a function. The heap can only be accessed by system calls such as malloc that request a memory allocation from the OS. Heap memory must be explicitly given back to the OS via a free system call. In C++, you can malloc memory using the new operator, and free it with del : SomeClass new_object = new SomeClass(...); del new_object;
C vs C++ strings In C, there is no string data type. A string is just an array of characters: char* some_str = Hello, world! ; Strings in C are null-terminated, which means the last character of the char array is the null byte, \0. This is to let functions know when the string actually ends! In C++, there is a string type in the std library. This is just a wrapper around C strings with some fancy functions. You can access the character array with the c_str() function: std::string another_str = Hey, everyone! ; char* the_real_str = another_str.c_str();
File I/O File operations: 1. Open a file : FILE pointer_name = fopen ("file_name", "Mode"); 2. Close a file : fclose(fp); 3. Reading a file : fscanf(fp, "%s", buffer) // read a string from the file until whitespace is encountered; 4. Writing to a file : fputc(ch, fp); // likewise fprintf can be used to write in the file. Modes: Mode r : It is a read only mode, Mode w : It is a write only mode Mode a : Using this mode Content can be appended
GDB GDB is a debugger by GNU project, it helps in checking the flow of the code line by line. All program to be debugged in gdb must be compiled by gcc with the option "-g" turning on Start GDB (garbage) Run program (args if any) Break execution Single step execution Print variable gdb./garbage (gdb) run arg_1 arg_2 break source_filename:line_number (gdb) break garbage.c:8 Breakpoint 1 at 0x1f7b: file garbage.c, line 8. (gdb) s (gdb) n n: the debugger will step to the next source line. Each function call will be treat as a single source code line. print variable_name (gdb) print a $10 = 88
Additional Resources Linux man (short for manual ) pages have pages for most of the ANSI/ISO C functions. You can read these online at https://linux.die.net/man/ The C++ Standard Library can be useful: http://www.cplusplus.com/reference/ SoloLearn has a C++ tutorial: https://www.sololearn.com/course/cplusplus/