C
Table of Contents
1. Hello World
#include <stdio.h> // import library using #include
int main(int argc, char *argv[]) { // main function signature
printf("Hello World!\n"); // print
return 0; // main returns an integer return code
}
1.1. printf
printf takes in as input a format string, which specifies the general structure of the printed line, followed by arguments. Common format specifiers include:
| Format Specifier | Description |
|---|---|
%d |
Signed integer (decimal) |
%u |
Unsigned integer |
%x |
Hexadecimal, lowercase |
%X |
Hexadecimal, uppercase |
%s |
Strings |
%c |
Characters |
%f |
Floating point |
%e |
Scientific notation |
%p |
Pointers/memory addresses |
2. Control Flow
while (expression) {
statements;
}
for (init-statement; condition; inc-expression) {
statements;
}
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
3. Types
| Type | Description | Library |
|---|---|---|
int |
Signed integers | C |
unsigned int |
Unsigned integers | C |
float |
Floating point decimal | C |
double |
Higher precision floating point | C |
char |
Character | C |
long |
Longer integer | C |
long long |
Even longer integer | C |
int32_t |
32-bit signed integer | stdint.h |
uint32_t |
32-bit unsigned integer | stdint.h |
The number of bytes in a int depends on the computer. Use types such as int32_t to guarantee the size of an integer.
4. Constants, Enums, and Macros
The keyword const defines a constant:
const int DAYS = 7;
Can define a preprocessor macro using the #define directive:
#define PI (3.14159) // will replace every instance of PI with 3.14159
Can define enums:
enum cardsuit{DIAMONDS, SPADES, HEARTS, CLUBS};
We can also define and name our own types with typedef and struct:
typedef enum cardsuit{DIAMONDS, SPADES, HEARTS, CLUBS} suit_t;
typedef struct cardstruct {
int rank;
suit_t suit;
} card_t;