COMP2004
Programming Practice
2002 Summer School


Kevin Pulo
School of Information Technologies
University of Sydney


(page 1)


Using &






(page 2)


Code style





(page 3)


Indenting




(page 4)


Bad Indenting 1


double a_function(int a) {
int b = 0;
double c;
while(b < 100) {
if (a == b) {
c = 34.2; }
else
{ c = 12.8;
}
}
}


(page 5)


Bad Indenting 2


double a_function(int a) {
int b = 0;
double c;
while(b < 100) {
if (a == b) {
c = 34.2; }
else
{c = 12.8;
}
}
}


(page 6)


Good Indenting


double a_function(int a) {
int b = 0;
double c;
while(b < 100) {
if (a == b) {
c = 34.2;
} else {
c = 12.8;
}
}
}


(page 7)


Whitespace




(page 8)


Bad Vertical Whitespace


unsigned int numDigits(unsigned long x) {
return static_cast(log10(x)) + 1;
}
void getDigits(std::vector &digits, unsigned long number) {
unsigned int i, n;
n = numDigits(number);
digits.resize(n);
for (i = n - 1; i > 0; i--) {
digits[i] = number % 10;
number = number / 10;



}
digits[i] = number;
}
int main() {
unsigned int number;
while (std::cin >> number) {
std::vector digits;
getDigits(digits, number);
std::cout << digits[0];
for (int i = 1; i < digits.size(); i++)
std::cout << ", " << digits[i];
std::cout << std::endl;
}
}



(page 9)


Good Vertical Whitespace


unsigned int numDigits(unsigned long x) {
return static_cast(log10(x)) + 1;
}


void getDigits(std::vector &digits, unsigned long number) {
unsigned int i, n;

n = numDigits(number);
digits.resize(n);
for (i = n - 1; i > 0; i--) {
digits[i] = number % 10;
number = number / 10;
}
digits[i] = number;
}


int main() {
unsigned int number;

while (std::cin >> number) {
std::vector digits;
getDigits(digits, number);

std::cout << digits[0];
for (int i = 1; i < digits.size(); i++)
std::cout << ", " << digits[i];
std::cout << std::endl;
}
}


(page 10)


Horizontal Whitespace











(page 11)


Identifiers




(page 12)


Bad Identifiers




(page 13)


Bad Identifiers





(page 14)


Structure




(page 15)


Comments





(page 16)


Comments




(page 17)


Comment syntax



int i; // Comment to end-of-line
int i; /* Comment with begin and end */

int i;
#if 0
Large block comment
#endif


(page 18)


Comment syntax



if ((d >= 1) && (d /*<=*/ maxDays)) if ((d >= 1) /* && (d /*<=*/ maxDays)*/) if ((d >= 1) maxDays)*/)


(page 19)


Comment syntax




(page 20)


Bracketing


if (a == b) do_something();

if (b == c)
{
part_1();
part_2();
}
else
something_else();


(page 21)


Another bracketing style


if (a == b) {
do_something();
}

if (b == c) {
part_1();
part_2();
} else {
something_else();
}


(page 22)


Simple g++ errors


1: #include
2: int main() {
3: int i = 42;
4: int* p = *i;
5: cout << &p << endl;
6: }
bash$ g++ -Wall -g -o prog prog.ccprog.cc: In function `int main()':
prog.cc:4: invalid type argument of `unary *'



(page 23)