mirror of
https://github.com/LCTT/TranslateProject.git
synced 2024-12-29 21:41:00 +08:00
149 lines
7.3 KiB
Markdown
149 lines
7.3 KiB
Markdown
|
[#]: subject: "C vs. Go: Comparing programming languages"
|
||
|
[#]: via: "https://opensource.com/article/23/4/c-vs-go-programming-languages"
|
||
|
[#]: author: "Jim Hall https://opensource.com/users/jim-hall"
|
||
|
[#]: collector: "lkxed"
|
||
|
[#]: translator: " "
|
||
|
[#]: reviewer: " "
|
||
|
[#]: publisher: " "
|
||
|
[#]: url: " "
|
||
|
|
||
|
C vs. Go: Comparing programming languages
|
||
|
======
|
||
|
|
||
|
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][1] 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][2] 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:
|
||
|
|
||
|
- Use the `+=`_add-to-self_ operator to write `sum = sum + count` more succinctly as `sum += count`. C can use this style, as well.
|
||
|
- Use the [assign-and-infer-type operator][3] to say `count := 1` rather than `var count int` followed by `count = 1`. The `:=` syntax both defines and initializes the count variable.
|
||
|
- 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][4].
|
||
|
|
||
|
### 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][5].
|
||
|
- 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`.
|
||
|
|
||
|
--------------------------------------------------------------------------------
|
||
|
|
||
|
via: https://opensource.com/article/23/4/c-vs-go-programming-languages
|
||
|
|
||
|
作者:[Jim Hall][a]
|
||
|
选题:[lkxed][b]
|
||
|
译者:[译者ID](https://github.com/译者ID)
|
||
|
校对:[校对者ID](https://github.com/校对者ID)
|
||
|
|
||
|
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||
|
|
||
|
[a]: https://opensource.com/users/jim-hall
|
||
|
[b]: https://github.com/lkxed/
|
||
|
[1]: https://opensource.com/article/17/6/getting-started-go
|
||
|
[2]: https://www.redhat.com/sysadmin/command-basics-printf?intcmp=7013a000002qLH8AAM
|
||
|
[3]: https://go.dev/ref/spec#Short_variable_declarations
|
||
|
[4]: https://go.dev/play/p/pt5mfRDR0rh
|
||
|
[5]: https://pkg.go.dev/fmt
|