Philip Guo (Phil Guo, Philip J. Guo, Philip Jia Guo, pgbovine)

Hello World in C and Python

I gave a guest lecture today in a compilers class and spent most of the hour comparing C and Python. I dissected the following pair of code examples.

Here's a Python program that prints "hello world" using string concatenation:

x = "hello"
y = " world"
z = x + y
print z

And here's the analogous C program with the proper boilerplate so that reasonable compilers don't complain:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  char* x = strdup("hello");
  char* y = strdup(" world");
  char* z = (char*)malloc(strlen(x) + strlen(y) + 1);
  strcpy(z, x);
  strcat(z, y);
  return 0;

Of course, there are ways to make the C code more compact. But a clean solution that uses dynamic memory allocation is going to be daunting to novices.

This simple pair of examples seeded a good discussion about:

  • Readability: Which version is easier for novices to grok?
  • Compilation: bytecode vs. machine code compilation
  • Memory Allocation: automatic vs. manual
  • Complexity: What's that extra 1 doing in the malloc?
  • Performance: Which version is faster and why?
  • Security: What happens if you lazily declare z to be fixed size and allow x or y to come from user input?
Subscribe to email newsletter
Donate to help pay for web hosting costs

Created: 2014-11-05
Last modified: 2014-11-05
Related pages tagged as programming:
Related pages tagged as computing education: