Open-source News

C vs. Go: Comparing programming languages

opensource.com - Mon, 04/24/2023 - 15:00
C vs. Go: Comparing programming languages Jim Hall Mon, 04/24/2023 - 03:00

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 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 55How 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.

Programming and development Red Hat Developers Blog Programming cheat sheets Try for free: Red Hat Learning Subscription eBook: An introduction to programming with Bash Bash shell scripting cheat sheet eBook: Modernizing Enterprise Java An open source developer's guide to building applications Register for your free Red Hat account 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.

Use a simple counting program to compare the venerable C language with modern Go.

Image by:

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

Go programming language Programming What to read next This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License. Register or Login to post a comment.

How to Compile and Install OpenSSH from Source in Linux

Tecmint - Mon, 04/24/2023 - 13:31
The post How to Compile and Install OpenSSH from Source in Linux first appeared on Tecmint: Linux Howtos, Tutorials & Guides .

OpenSSH is a free and open source, full implementation of the SSH protocol 2.0, which provides a number of tools for securely accessing and managing remote computer systems, and managing authentications keys, such as

The post How to Compile and Install OpenSSH from Source in Linux first appeared on Tecmint: Linux Howtos, Tutorials & Guides.

How to Install OpenSSH Server In Linux

Tecmint - Mon, 04/24/2023 - 12:31
The post How to Install OpenSSH Server In Linux first appeared on Tecmint: Linux Howtos, Tutorials & Guides .

Being a network administrator requires deep knowledge of remote login protocols such as rlogin, telnet, and ssh. The one I will discuss in this article is ssh. SSH is a secure remote protocol that

The post How to Install OpenSSH Server In Linux first appeared on Tecmint: Linux Howtos, Tutorials & Guides.

MimiPenguin – Display (Hack) Login Passwords of Linux Users

Tecmint - Mon, 04/24/2023 - 11:54
The post MimiPenguin – Display (Hack) Login Passwords of Linux Users first appeared on Tecmint: Linux Howtos, Tutorials & Guides .

MimiPenguin is a free and open source, simple yet powerful Shell/Python script used to dump the login credentials (usernames and passwords) from the current Linux desktop user and it has been tested on various

The post MimiPenguin – Display (Hack) Login Passwords of Linux Users first appeared on Tecmint: Linux Howtos, Tutorials & Guides.

How to Set Passwordless SSH Login on RHEL 8

Tecmint - Mon, 04/24/2023 - 11:00
The post How to Set Passwordless SSH Login on RHEL 8 first appeared on Tecmint: Linux Howtos, Tutorials & Guides .

With the release of RHEL 8, you get to experience what the real product will be like and test some of its functionalities. If you are eager to test RHEL 8 you can signup

The post How to Set Passwordless SSH Login on RHEL 8 first appeared on Tecmint: Linux Howtos, Tutorials & Guides.

How to Install and Run Rust on Linux

Tecmint - Mon, 04/24/2023 - 10:07
The post How to Install and Run Rust on Linux first appeared on Tecmint: Linux Howtos, Tutorials & Guides .

Rust (commonly known as Rust-Lang) is a relatively new, open-source practical systems programming language that runs extremely fast, prevents segfaults, and guarantees thread safety. It is a safe and concurrent language developed by Mozilla

The post How to Install and Run Rust on Linux first appeared on Tecmint: Linux Howtos, Tutorials & Guides.

GNU Linux-libre 6.3-gnu Cleans Up New ath12k WiFi Driver, Other New Additions

Phoronix - Mon, 04/24/2023 - 09:00
Following this afternoon's release of the Linux 6.3 kernel, GNU Linux-libre 6.3-gnu has already been released as this downstream kernel flavor that removes support for loading binary-only modules and trying to de-blob other driver code that otherwise depends upon "non-free" code...

GNU Linux-libre 6.3-gnu Cleans Up New ath12k WiFi Driver, Other New Additions

Phoronix - Mon, 04/24/2023 - 09:00
Following this afternoon's release of the Linux 6.3 kernel, GNU Linux-libre 6.3-gnu has already been released as this downstream kernel flavor that removes support for loading binary-only modules and trying to de-blob other driver code that otherwise depends upon "non-free" code...

Message to Red Hat associates today

Red Hat News - Mon, 04/24/2023 - 08:00
<p><em>Editor’s note: Earlier today, president and chief executive officer of Red Hat, Matt Hicks, shared the following email with Red Hatters.&nbsp;</em></p> <p>—</p> <p>Hi all,</p> <p>There have been several occasions where we’ve had to make tough decisions at Red Hat, but no decision has been harder than the one I must communicate to you today: We will reduce the associate base of Red Hat over the next few months. Our reductions will focus on g

Linux 6.3 Released With More Meteor Lake Enablement, Zen 4 Auto IBRS & Much More

Phoronix - Mon, 04/24/2023 - 03:30
Linus Torvalds just released Linux 6.3 as the newest stable kernel version...

Pages