Skip to main content

C Basics

For Loops

point to note: declaring a variable in the loop init part is only supported after c99

int main() {
for (int i = 0; i < 10; i++) {
printf("%d", i);
}
}

Functions

Pass by value

similar with c++

int multiply(int a, int b) {
return a*b;
}

Pass by reference

using swap as an example, the function takes in two pointer

void swap(int *a, int *b) {
double temp = *a;
*a = *b;
*b = temp;
}

Math Library

include the math library

#include <math.h>

link math library when compile (using the lm flag)

gcc sample.c -o sample -lm

Array

when a pointer is referring to an array, it is storing the address of the 1st slot of the array

void increment(int *arr) {
for (int i = 0; i < 4; i++) {
(*arr) = (*arr) * 1.1;
i++; // go to next slot in the array
}
}

C-String

string in c is an array of char

point to note: when we want to stores string of length 11 into an array, the array size have to be 12 because of the null character at the end of a c-string

String Manipulation

FunctionOperation
strcpy(char s1[], char s2[])copy from s2 to s1, s2 not changed
strcat(char s1[], char s2[])append s2 to s1, s2 not changed
strcmp(char s1[], char s2[])negative if s1 is smaller, 0 if equal, positive if s1 larger
strlen(char s1[])return the length of the string stored in the char array

Convert between upper and lower case

'A' + 32      // convert upper to lower
'a' - 32 // convert lower to upper