Oct 15 GPE Recitation

C/C++ : A Quick Review

The Rule of Identifiers (識別子,變數及函式名稱)

  • 只能使用字母、數字、底線,但數字不能在開頭
  • 不能跟 keyword 或 global identifier 同名

Formatted Input with scanf()

  • "%d%d" → "1-20" "1-20"
  • "%d/%d" → "▲5/▲96" "▲5▲/▲96"
  • 數字前的會被忽略
  • 如果 format string 中有一個或多個空白字元 (、\t、\n、\r 等屬空白字元),scanf() 會不停讀取空白字元,直到遇到非空白字元
  • "%1d%1d%1d" → "123"

Operators

  • C Operator Precedence & Associativity
  • i<j<k means (i<j)<k, where i<j will evaluate to 1 or 0 and then compared to k
  • nonzero operand → true, zero operand → false
  • if (5+3>=0 || 6/0==0) { }
    如果左邊的運算元就能決定結果 (1 or 0),右邊的運算元就不會被執行

Undefined Behavior

  • Assignment operators and increment/decrement operator will modify their operands, we say that they have "side effect".
  • k=++i+j++; → i=i+1; k=i+j; j=j+1;
  • c=(b=a+2)-(a=1);
  • j=i*i++;

Switch/Case

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;
}
  • switch (var) → var can be int or char (treated as int), but cannot be float or string
  • case const: → const must be int or char, just like above, 5+10 is acceptable, but n+10 is not (not a constant)

Loops

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);
  • for ( ; ; ) → omit expression2
    It defaults to a true value, so
    this is equivalent to while (1)
  • for (d=2; d<n && n%d!=0; d++);
    → the null statement

Functions (Only C++ Supports Overloading)

#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;
}

Array Initialization

// 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] = "";

C Strings

// Type A: using pointers
char* str = "Hello, world!";
// Type B: using arrays
char str[20] = "Hello, world!";
  • "a" is for strings, 'a' is for characters.
  • str = "test"; → only in type A
    because in type B, typeof str is char[20] != char*
  • str[7] = 'W'; → only in type B
    because in type A, str points to a string literal
  • Include string.h to manipulate C strings and arrays.
  • Using C++ string class may be easier if you know OO.

Structures/Unions/Enumerations

// 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];

Dynamic Memory Allocation

// 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

The "static" Keyword

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]);
  • Static local variables:
    lifetime → program execution; visibility → local scope
  • Static global variables:
    lifetime → ″ visibility → internal (translation unit)
  • Within the array type derivation:
    at least as many elements as specified by the size expression
  • Static member variables inside class definitions (C++ only):
    a shared copy exists, regardless of instances

Common Programming Mistakes

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'

Common Programming Mistakes

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

Common Programming Mistakes

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;

Miscellaneous

#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);

National Chiao Tung University
Y.W. Pu

C/C++ : A Quick Review

By Yu-wen Pwu

C/C++ : A Quick Review

For the NCTU GPE Recitation on Oct 15

  • 1,184