gcc stack.c rpn.c
printf("Enter format string: "); char format[200]; /* be safe? */ scanf("%s", format); /* scan reads from stdin */ printf(format, name, age);
#include <string.h> char first[40], last[40]; ... cout << "Length of " << first << ": " << strlen(first); // first becomes last: strcpy(first, last); // check if they are ordered if ( strcmp(first, last) < 0 ) cout << first << " before " << last << endl;
int strlen(const char str[]) // const: won't change array contents { int len = 0; while ( str[len] != '\0' ) ++len; return len; }
strcpy(animal, "giraffe");
#define LEN 100 char word[LEN]; printf("Enter word: "); scanf("%s", word); // trusting user! word[LEN - 1] = '\0'; // but not completely... if ( word[0] != '\0' ) // at least one char { char last = word[strlen(word) - 1]; if ( last != 's' && last != 'S' ) { word[LEN - 2] = '\0'; // ensure space... strcat(word, "s"); // no need to use strncat } }
gcc array.c
double underlying_data[7]; double *numbers = &underlying_data[3]; ... numbers[-1] = ... ... numbers[3] = ... // (legal values from -3 to +3)
0 | 1 | 2 | 3 | 4 | 5 | |
---|---|---|---|---|---|---|
0 | ||||||
1 | ||||||
2 | ||||||
… | ||||||
9 |
#define X Yall occurrances of X (case-sensitive) are replaced by Y
#define MAX_LEN 50so
int nums[MAX_LEN];translates to
int nums[50];
#define MAX_LEN 50; int nums[MAX_LEN];translates to
int nums[50;];which won't compile
#define MAX_STRING_LENGTH 100 #define MAX_DECLARED_STRING MAX_STRING_LENGTH + 1 char name[MAX_DECLARED_STRING]; /* but see discussion below */
#define max(a, b) a > b ? a : b #define sqr(x) x * x
#define name value #define name(arguments) value
double y = max(u, v); i = sqr(j);translates to
double y = u > v ? u : v; i = j * j;
i / j * j;which is equivalent to (i / j) * j; should write:
#define sqr(x) (x * x)
#define sqr(x) ((x) * (x))
#define NOCOPY(T) T(const T&)=delete;T(const T&&)=delete;void operator=(const T&)=delete;void operator=(const T&&)=delete;which can be used as
class Roster { ... NOCOPY(Roster); };
#define assert(test) ((test) ? cerr \ : (cerr << "Assertion failure on line " \ << __LINE__ << " of " << __FILE__ \ << ": " << #test << endl))
assert(x > 0);gives
((x > 0) ? cerr : (cerr << "Assertion failure on line " << 25 << " of " << "prog3.cpp" << ": " << "x > 0" << endl));
#ifdef _Windows cout << "This is compiled for Microsoft Windows." << endl; #else cout << "This is compiled for a non-Microsoft Windows system." << endl; #endif
#if 0 ... errant code ... #endif
// comment out following for release builds #define DEBUG ... #ifdef DEBUG ... #endif
// // util.h: utilities // #ifndef _util_h #define _util_h declarations, etc. #endif