Yu-wen Pwu
Department of Computer Science, NCTU
switch (a) {
case 1:
// if a == 1, do the following
break;
case 2:
// if a == 2, do the following
break;
default:
// else, do the following
break;
}
for (int a=1, b=1; a<=100; a++, b+=2) {
// do sth
}
int a=1, b=1;
while (a<=100) {
// do sth
a++;
b+=2;
}
int a=1, b=1;
do {
// do sth
a++;
b+=2;
} while (a<=100);
#include <stdio.h>
// Hint: Use C++ template may be better.
int get_max(int, int);
double get_max(double, double);
int main() {
printf("The maximum is %d.", get_max(10, 20));
printf("The maximum is %f.", get_max(3.14, 1.732));
return 0;
}
int get_max(int a, int b) {
int max = a>b ? a : b;
return max;
}
double get_max(double a, double b) {
double max = a>b ? a : b;
return max;
}
// initialize to 1, 2, 0, 0, 0, ...
int arr[10] = {1, 2};
// initialize to 5, 0, 0, 0, ...
int arr[10] = {5};
// initialize to 0, 0, 0, ...
int arr[10] = {0};
// [C++ only] initialize to 0, 0, 0, ...
int arr[10] = {};
// also initialize to 0, 0, 0, ...
static int arr[10];
// initialize to 'a', 'b', 'c', '\0', '\0', '\0', ...
char str[32] = "abc";
// initialize to '\0', '\0', '\0', ...
char str[32] = "";
// Type A: using pointers
char* str = "Hello, world!";
// Type B: using arrays
char str[20] = "Hello, world!";
// use union to save space
// n can mix multiple types
typedef struct {
enum { INT_VAL, DOUBLE_VAL } type;
union {
int i;
double d;
} num;
} number;
number n[100];
// In C
#include <stdlib.h>
int* p1 = (int*) malloc(20*sizeof(int));
int* p2 = (int*) calloc(20, sizeof(int)); // zero-initialize
int* p3 = (int*) realloc(p2, 30*sizeof(int));
if (p1 != NULL) {
// do sth
free(p1);
p1 = NULL;
}
// In C++
try {
int *p = new int[20];
} catch (std::bad_alloc& e) {
// failed
}
// do sth
delete[] p;
p = nullptr; // C++11 and above
void foo() {
int a = 0;
static int b = 0;
a += 1;
b += 1;
printf("a = %d, b = %d\n", a, b);
}
void bar(double a[static 10]);
double d;
scanf("%f", &d);
// should be "%lf"
char c;
scanf("%c", &c);
// use " %c" to skip white space
int i; char c;
scanf("%d", &i);
c = getchar();
// then c == '\n'
int a, b; float f;
f = (float) a/b;
// it means ((float) a)/b
#define int_ptr int*
int_ptr p1, p2, p3;
// use typedef int* int_ptr
int i;
scanf("%d", &i);
int arr[i];
// only C99 supports variable length arrays
int func(int arr[][], int len) {
// do sth
}
// 第二維以後要指明 int arr[][100]
char str[20];
scanf("%s", str);
// 如果要讀一整行 (含空白),應使用 fgets(str , 20 , stdin);
// gets(str); is unsafe (can lead to buffer overflows) !!
struct node {
int data;
struct node* next;
};
node* head;
// 在 C 語言中只能寫 struct node* head;
// 或寫成 typedef struct { ... } node;
#include <stdlib.h>
// C string to double
double atof(const char* str);
double strtod(const char* str, char** endptr);
// C string to int
int atoi(const char* str);
// C string to long int
long int atol(const char* str );
long int strtol(const char* str, char** endptr, int base);
By Yu-wen Pwu
For the NCTU GPE Recitation on Oct 15