After this lesson, you will be able to: Use C's data types, operators, control flow, functions, and main signature.
Basic syntax. C is small; the danger is in details.
Read each line.
#include <stdio.h>#include <stdbool.h>int main(void) {// Primitive types, sizes are platform-dependent, EXCEPT stdint.hint n = 42; // typically 32-bitlong ln = 100000L; // at least 32-bitlong long lln = 999LL; // at least 64-bitfloat f = 3.14f;double d = 3.14159;char c = 'A'; // 1 byte; really a small intbool b = true; // from stdbool.h// Use stdint.h for portable widths// int32_t, int64_t, uint8_t, uint64_t, exact sizes// Operatorsint sum = n + 8;int rem = n % 5;int isEven = (n % 2 == 0);// Control flowif (n > 0) printf("pos\n");else if (n == 0) printf("zero\n");else printf("neg\n");for (int i = 0; i < 5; i++) printf("%d\n", i);int j = 0;while (j < 5) { printf("%d\n", j); j++; }switch (n) {case 0: printf("zero\n"); break;case 42: printf("answer\n"); break;default: printf("other\n");}return 0;}
Declare before use; main can take args.
#include <stdio.h>// Forward declarationint add(int a, int b);int main(int argc, char *argv[]) {if (argc < 2) {fprintf(stderr, "usage: %s <name>\n", argv[0]);return 1;}printf("Hello, %s\n", argv[1]);printf("2 + 3 = %d\n", add(2, 3));return 0;}int add(int a, int b) {return a + b;}
%d / %i, int. %u, unsigned. %ld, long. %lld, long long. %f, float/double. %.2f, 2 decimals. %c, char. %s, string. %p, pointer. %x, hex. %%, literal percent. Mismatched format + type is undefined behavior. Always match: `printf("%d\n", 3.14)` is wrong.
Using `int` for sizes (use `size_t`). Mismatched printf format and type. Integer overflow without thinking. INT_MAX + 1 is undefined behavior in C. Forgetting `void main()` is non-standard. Use `int main(void)` or `int main(int argc, char *argv[])`.
Pick the bug.
Sign in and purchase access to unlock this lesson.