C Language
C Language Hello World #include <stdio.h> int main() { printf("hello, world\n"); return 0; } With arguments #include <stdio.h> int main(int argc, char* argv[]) { printf("arg count: %i\n", argc); for (int i=1; i<argc; i++) { printf("argv: %s\n", argv[i]); } return 0; } 编译与运行 gcc hello.c ./a.out comments // comment /* multiline comments */ Command-line arguments #include <stdio.h> int main(int argc, char *argv[]) { int i; for (i=1; i<argc; i++) { printf("%s%s", argv[i], (i < argc-1) ? " ": ""); } printf("\n"); return 0; } argc: argument count argv: argument vector Includes #include <xxx.h>: search in standard places, ex: /usr/include #include "yyy.h": search in working dir Variables Data Types Data Type Size Value Range Format boolean 1 byte 1 char 1 -128 ~ 127 %d unsigned char 1 0 ~ 255 %u short 2+(dependent on complier) -32768 ~ 32767 %d unsigned short 2+ 0 ~ 65535 %u int short to long(dependent on complier) -2147483648 ~ 2147483647 %d unsigned int short to long 0 ~ 2^32 %u long 4+(dependent on complier) %ld unsigned long 4+ %lu float 4 3.4e-38 to 3.4e+38 %f double 4 1.7e-308 to 1.7e+308 Type Cast int x = 1; // signed与unsigned互转,保持二进制表示不变,值可能改变 unsigned int ux = (unsigned int) x; // 短类型转长类型 // 对于signed类型(Two's Complement编码)在左侧补最高位bit的值(sign extension) // 对于unsigned类型,在左侧补0(zero extension) long lx = (long) x; // 长类型转短类型,截断高位,然后根据编码类型(signed or unsigned)解释数值 short sx = (short) lx; Declaring and Instantiating Variables // declarating int year; // instantiating year = 2022; // Declaring and instantiating simultaneously int year = 2022 // Constant const float pi = 3.14; Symbolic Constants #define LOWER 0 #define UPPER 300 #define STEP 20 Enum Constants // starts at 0, next 1, etc... enum boolean { NO, YES }; // values are specified enum escapes { BELL = '\a', BACKSPACE = '\b', TAB = '\t', NEWLINE = '\n', VTAB = '\v', RETURN = '\r' }; /* FEB = 2, MAR = 3, etc. */ enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }; Array int ndigit[10]; for (i = 0; i < 10; ++i) { ndigit[i] = 0; } // assigns values to first 5 data int myarray[10] = {20, 30, 40, 50, 100}; int myarray[] = {20, 30, 40, 50, 100}; // size size = sizeof(myArray) / sizeof(int) 2-D Array // definition char daytab[2][13] = { {0, 31, 28, ..., 31}, {0, 31, 29, ..., 31} }; // get value daytab[i][j]; // passed to function f(int daytab[2][13]) { ... } f(int daytab[][13]) { ... } /* the number of row is irrelevant */ f(int (*daytab)[13]) { ... } /* a pointer to an array of 13 integers */ sizeof size_t:unsigned interger, defined in <stddef.h> #define NKEYS (sizeof keytab / sizeof(struct key)) #define NKEYS (sizeof keytab / sizeof(keytab[0])) Character string every character string has a ’\0’ at the end ...