C vs. Go: Comparing programming languages

Use a simple counting program to compare the venerable C language with modern Go.
5 readers like this.
Pair programming

WOCinTech Chat. Modified by Opensource.com. CC BY-SA 4.0

Go is a modern programming language that derives much of its history from the C programming language. As such, Go is likely to feel familiar to anyone who writes programs in C. Go makes it easy to write new programs while feeling familiar to C programmers but avoiding many of the common pitfalls of the C programming language.

This article compares a simple C and Go program that adds the numbers from one to ten. Because this program uses only small values, the numbers won't grow to be too big, so they only use plain integer variables. Loops like this are very common in programming, so this simple program makes it easy to compare C and Go.

How to do loops in C

The basic loop in C is the for loop, which allows you to iterate through a set of values. The basic syntax of the for loop is:

for (start condition ; end condition ; action after each iteration) { things to do inside the loop ; }

You can write a for loop that prints the numbers from one to ten by setting the starting condition to count = 1 and the ending condition to count <= 10. That starts the loop with the count variable equal to one. The ending condition means the loop continues as long as the count variable is less than or equal to ten.

After each iteration, you use count = count + 1 to increment the value of the count variable by one. Inside the loop, you can use printf to print the value of the count variable:

for (count = 1; count <= 10; count = count + 1) {
  printf("%d\n", count);
}

A common convention in C programming is ++, which means "add one to something." If you write count++, that's the same as count = count + 1. Most C programmers would use this to write the for loop using count++ for the action after each iteration, like this:

for (count = 1; count <= 10; count++) {
  printf("%d\n", count);
}

Here's a sample program that adds the numbers from one to ten, then prints the result. Use the for loop to iterate through the numbers, but instead of printing the number, add the numbers to the sum variable:

#include <stdio.h>

int main() {
  int sum;
  int count;
  puts("adding 1 to 10 ..");
  sum = 0;

  for (count = 1; count <= 10; count++) {
    sum = sum + count;
  }

This program uses two different C functions to print results to the user. The puts function prints a string that's inside quotes. If you need to print plain text, puts is a good way to do it.

The printf function prints formatted output using special characters in a format string. The printf function can print lots of different kinds of values. The keyword %d prints a decimal (or integer) value.

If you compile and run this program, you see this output:

adding 1 to 10 ..
The sum is 55

How to do loops in Go

Go provides for loops that are very similar to C for loops. The for loop from the C program can be directly translated to a Go for loop with a similar representation:

for count = 1; count <= 10; count++ {
  fmt.Printf("%d\n", count)
}

With this loop, you can write a direct transition to Go of the sample program:

package main
import "fmt"

func main() {
  var sum, count int
  fmt.Println("adding 1 to 10 ..")

  for count = 1; count <= 10; count++ {
    sum = sum + count
  }
  fmt.Printf("The sum is %d\n", sum)
}

While the above is certainly a valid and correct Go, it's not the most idiomatic Go. To be idiomatic is to use expressions that are natural to a native speaker. A goal of any language is effective communication, this includes programming languages. When transitioning between programming languages, it is also important to recognize that what is typical in one programming language may not be exactly so in another, despite any outward similarities.

To update the above program using the more idiomatic Go, you can make a couple of small modifications:

  1. Use the += add-to-self operator to write sum = sum + count more succinctly as sum += count. C can use this style, as well.

  2. Use the assign-and-infer-type operator to say count := 1 rather than var count int followed by count = 1. The := syntax both defines and initializes the count variable.

  3. Move the declaration of count into the for loop header itself. This reduces a bit of cognitive overhead, and increases readability by reducing the number of variables the programmer must mentally account for at any time. This change also increases safety by declaring variables as close as possible to their use and in the smallest scope possible. This reduces the likelihood of accidental manipulation as the code evolves.

The combination of the changes described above results in:

package main
import "fmt"

func main() {
  fmt.Println("adding 1 to 10 ..")
  var sum int
  for count := 1; count <= 10; count++ {
    sum += count
  }

  fmt.Printf("The sum is %d\n", sum)
}

You can experiment with this sample program in the Go playground with this link to go.dev.

C and Go are similar, but different

By writing the same program in two programming languages, you can see that C and Go are similar, but different. Here are a few important tips to keep in mind when transitioning from C to Go:

  • In C, every programming instruction must end with a semicolon. This tells the compiler where one statement ends and the next one begins. In Go, semicolons are valid but almost always inferred.

  • While most modern C compilers initialize variables to a zero value for you, the C specification says that variables get whatever value was in memory at the time. Go values are always initialized to their zero value. This helps make Go a more memory safe language. This distinction becomes even more interesting with pointers.

  • Note the use of the Go package specifier on imported identifiers. For example, fmt for functions that implement formatted input and output, similar to C's printf and scanf from stdio.h. The fmt package is documented in pkg.go.dev/fmt.

  • In Go, the main function always returns with an exit code of 0. If you wish to return some other value, you must call os.Exit(n) where n is typically 1 to indicate an error. This can be called from anywhere, not just main, to terminate the program. You can do the same in C using the exit(n) function, defined in stdlib.h.

photo of Jim Hall
Jim Hall is an open source software advocate and developer, best known for usability testing in GNOME and as the founder + project coordinator of FreeDOS.

Comments are closed.

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.