aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • Software Engineering

C Vs. Go: Comparing Programming Languages

  • aster_cloud
  • April 30, 2023
  • 4 minute read

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

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.


Partner with aster.cloud
for your next big idea.
Let us know here.



From our partners:

CITI.IO :: Business. Institutions. Society. Global Political Economy.
CYBERPOGO.COM :: For the Arts, Sciences, and Technology.
DADAHACKS.COM :: Parenting For The Rest Of Us.
ZEDISTA.COM :: Entertainment. Sports. Culture. Escape.
TAKUMAKU.COM :: For The Hearth And Home.
ASTER.CLOUD :: From The Cloud And Beyond.
LIWAIWAI.COM :: Intelligence, Inside and Outside.
GLOBALCLOUDPLATFORMS.COM :: For The World's Computing Needs.
FIREGULAMAN.COM :: For The Fire In The Belly Of The Coder.
ASTERCASTER.COM :: Supra Astra. Beyond The Stars.
BARTDAY.COM :: Prosperity For Everyone.

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.

Read More  The 2-Minute Test For Kubernetes Pod Security

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.
Read More  Manage OpenStack Using Terraform And Gitlab

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.

By: Jim Hall
Originally published at Opensource

Source: Cyberpogo


For enquiries, product placements, sponsorships, and collaborations, connect with us at [email protected]. We'd love to hear from you!

Our humans need coffee too! Your support is highly appreciated, thank you!

aster_cloud

Related Topics
  • C
  • Go
  • Go lang
  • Programming
  • Tutorials
You May Also Like
Web
View Post
  • Engineering
  • Software Engineering

Mastering the Art of Load Testing for Web Applications

  • November 29, 2023
View Post
  • Design
  • Software Engineering

Organizing “spaghetti” Software So It Can Be Easily Modified

  • October 17, 2023
View Post
  • Software Engineering
  • Technology

Introducing Code Llama, A State-Of-The-Art Large Language Model For Coding

  • August 25, 2023
Redis logo
View Post
  • Data
  • Platforms
  • Software Engineering

Redis 7.2 Sets New Standard For Developers To Harness The Power Of Real-Time Data

  • August 15, 2023
View Post
  • Software
  • Software Engineering

End-to-End Secure Evaluation of Code Generation Models

  • August 11, 2023
View Post
  • Software
  • Software Engineering

Simplifying Creation Of Go Applications On Google Cloud

  • August 6, 2023
Python | Code
View Post
  • Engineering
  • Software Engineering

LPython: Novel, Fast, Retargetable Python Compiler

  • July 31, 2023
Java
View Post
  • Software Engineering

Is Migrating From Java 11 To Java 17 Worth It?

  • July 28, 2023

Stay Connected!
LATEST
  • Birthday Cake 1
    How ChatGPT Altered Our World in Just One Year
    • November 30, 2023
  • OpenAI 2
    Sam Altman Returns As CEO, OpenAI Has A New Initial Board
    • November 30, 2023
  • Web 3
    Mastering the Art of Load Testing for Web Applications
    • November 29, 2023
  • Data center. Servers. 4
    Intel Granulate Optimizes Databricks Data Management Operations
    • November 27, 2023
  • Ubuntu. Chiselled containers. 5
    Canonical Announces The General Availability Of Chiselled Ubuntu Containers
    • November 25, 2023
  • Cyber Monday Sale. Guzz. Ideals collection. 6
    Decode Workweek Style with guzz
    • November 23, 2023
  • Guzz. Black Friday Specials. 7
    Art Meets Algorithm In Our Exclusive Shirt Collection!
    • November 23, 2023
  • Presents. Gifts. 8
    25 Besties Bargain Bags Below $100 This Black Friday 2023
    • November 22, 2023
  • Electronics 9
    Top 10+1 You Can’t Do Without For The Holidays: Electronics Edition.
    • November 20, 2023
  • Microsoft. Windows 10
    Ousted Sam Altman To Lead New Microsoft AI Team
    • November 20, 2023
about
Hello World!

We are aster.cloud. We’re created by programmers for programmers.

Our site aims to provide guides, programming tips, reviews, and interesting materials for tech people and those who want to learn in general.

We would like to hear from you.

If you have any feedback, enquiries, or sponsorship request, kindly reach out to us at:

[email protected]
Most Popular
  • Oracle | Microsoft 1
    Oracle Cloud Infrastructure Utilized by Microsoft for Bing Conversational Search
    • November 7, 2023
  • Riyadh Air and IBM 2
    Riyadh Air And IBM Sign Collaboration Agreement To Establish Technology Foundation Of The Digitally Led Airline
    • November 6, 2023
  • Ingrasys 3
    Ingrasys Unveils Next-Gen AI And Cooling Solutions At Supercomputing 2023
    • November 15, 2023
  • Cloud 4
    DigitalOcean Currents Report Finds That Adoption Of AI/ML, And Investments In Cybersecurity And Multi-Cloud Strategies Are On The Rise At Small Businesses
    • November 9, 2023
  • Portrait of Rosalynn Carter, 1993 5
    Former First Lady Rosalynn Carter Passes Away at Age 96
    • November 19, 2023
  • /
  • Technology
  • Tools
  • About
  • Contact Us

Input your search keywords and press Enter.