C and C++ Notes
Basics
-
How to compile:
1
gcc -Wall -o foo foo.c
-
Input in C:
1 2 3 4 5
char foo[100]; int bar; fgets(foo, sizeof(foo), stdin); scanf("%d", &bar); getchar(); // must be added after scanf. It handels /n
-
Input in C++:
1 2
string foo; getline(cin, foo);
-
When two types sum, a promotion happens. When a type is passed to a function, a demotion happens.
-
Prefix and postfix
++
--
differ when used in an assignment:1 2 3
int a = 1; int b = ++a; // a = 2, b = 2 int b = a++; // a = 3, b = 2
-
0 is false. Everything else is true.
-
In
argv
, the first name is the program’s name. -
puts()
will append\n
to the end of the string and print.
Dynamic Memory Allocation
-
In C:
1 2 3 4 5 6
int* foo; foo = (int*) malloc(sizeof(int) * 10); if (foo == NULL) { // blah blah } free(foo);
-
In C++:
T* ptr = new T(value)
is equivalent toT* ptr = new T[1] {value}
((value) and {value} can be omitted.) (delete [] ptr
for arrays;delete ptr
for single values.)
Makefiles
-
How to run:
1
make // if no extension
1 2
make -f Mymakefile.txt make
Templates
-
Generic Functions:
1 2 3 4 5 6 7 8 9
template <class T> T array_sum(T arr[], int size) { int i; T sum = arr[0]; for (i = 1; i < size; i ++) { sum = sum + arr[i]; } return sum; }
-
Generic Classes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
template <class T> class BoundedArray { T array[size]; public: BoundedArray(){}; T& operator[](int); // overloaded access operator }; template<class T> T& BoundedArray<T>::operator[](int pos) { if ((pos < 0) || (pos >= size)) { exit(1); } return array[pos]; } // ... BoundedArray<int> intArray;
STL
-
Vectors:
1 2 3 4
#include <vector> // ... vector<int> vInt(5); vInt.push_back(1); // .clear, .size, .pop_back
-
Deques: (Double Ended Queues)
1 2
#include <deque> // .push_front, .pop_front
-
Lists: (Doubly Linked Lists) (No random access.)
-
Iterators:
1 2 3
vector<int> vInt; vector<int>::iterator vIterator; for (vIterator = vInt.begin(); vIterator != vInt.end(); vIterator++) {}
-
Set: (insert, erase, clear, empty, size, find, count)
-
Maps: (find, clear, erase, insert)
1 2
map<const char*, int, LessThanStr> months; months["january"] = 31;
Miscellaneous
-
When we initialize an int vector, int array, etc., they are filled with 0s.
-
The public interface is inherited to the inherited class. (The interface of the base class is a subset of the derived class.)
-
We must initialize static data members outside of the class:
1 2 3 4 5
class foo { static int var; } int foo::var = 0;
-
When we write to a file, the data is first stored in the buffer. When the buffer is flushed, the data is written into the file.
-
const
with pointers1 2 3 4
int a = 2; const int* ptr = &a; // constant data (2), not constant pointer int* const ptr_1 = &a; // constant pointer, not constant data const int* const ptr_2 = &a; // constant pointer and data
-
Auto-dereferencing in C++:
1 2 3
int foo = 1; int& bar = foo; bar = 2; // Both are 2 now