'Build Your Own Lisp' Solutions: 4.7

Q: What does the preprocessor command #ifndef do?


A: Checks if a token has already been defined earlier in the file, or in a previous file, then includes anything between it and #else or #endif.



'Build Your Own Lisp' Solutions: 4.6

Q: What happens when you pass printf a variable that does not match the pattern?

A:

#include <stdio.h>

int main(void)
{
  // This depends heavily on the kind of mistake you want to make. Some 
  // examples:

  // A character is really a number, so this is fine.
  printf("%c\n", 109);
  // And vice-versa.
  printf("%d\n", 'm');
  // A string really just points to the memory address of the first character,
  // and %d will try to interpret that address as a base ten number, so this
  // will be something different every time you run the program.
  printf("%d\n", "moo");

  // These examples all happen to give you something, but the compiler has no 
  // idea what to do with something like 'printf("%s\n", 13);', and will give 
  // you a Segment Fault error.

  return 0;
}
> ./wrong 
m
109
340750348


19-05-19 Weekly Links




19-05-12 Weekly Links - Classic Internet Edition



'Build Your Own Lisp' Solutions: 4.5

Q: What other patterns can be used with printf?


A: More than are worth memorizing (at least all at once). As the chapter states, it's best to check a good reference.



K&R Solutions - 1.19

Q: Write a function 'reverse(s)' that reverses the character string 's'. Use it to write a program that reverses the input one line at a time.

A:

#include <stdio.h>

// Using the same basic format is previous exercises and examples
#define MAXLINE 1000

int get_a_line(char s[], int lim);
void reverse(char s[]);

int main(void)
{
  char line[MAXLINE];

  while ((get_a_line(line, MAXLINE)) > 0) {
    reverse(line);
    printf("%s", line);
  }

  return 0;
}

int get_a_line(char s[], int lim)
{
  int c, i;

  for (i = 0; i < lim-1 && (c=getchar()) != EOF && c != '\n'; ++i) {
    s[i] = c;
  }

  if (c == '\n') {
    s[i] = c;
    ++i;
  }
  s[i] = '\0';

  return i;
}

void reverse(char s[])
{
  char temp[MAXLINE];
  int i, j;

  i = 0;
  while ((temp[i] = s[i]) != '\0')
    ++i;

  /* Reversing the newline looks ugly. In real life, we might strip that 
   * char of whitespace before reversing it, as per the last lesson. */
  j = 0;
  --i;
  s[i--] = '\n';
  while (i >= 0) {
    s[i] = temp[j];
    ++j;
    --i;
  }
}
./reverse 
hi
ih
sananab is a good blog
golb doog a si bananas
tacocat
tacocat


19-04-21 Weekly Links
<OBJECT SANDWICH-BAG
	(LOC KITCHEN-TABLE)
	(SYNONYM BAG SACK)
	(ADJECTIVE BROWN ELONGATED SMELLY)
	(DESC "brown sack")
	(FLAGS TAKEBIT CONTBIT BURNBIT)
	(FDESC
"On the table is an elongated brown sack, smelling of hot peppers.")
	(CAPACITY 9)
	(SIZE 9)
>


Retry Password


Debris From The Ariane 5 Accident