编程语言比较：C 和 Go
Go 语言 C 语言
![](/data/attachment/album/202305/23/181943xqq3sbwomkkcia3t.jpg)



> 
> 使用一个简单的计数程序比较古老的 C 语言和现代的 Go 语言。
> 
> 
> 


Go 是一种现代编程语言，它很大程度上源自于 C 编程语言。因此，对于写 C 程序的程序员来说，Go 应该会感觉很熟悉。[Go 让编写新程序变得容易](https://opensource.com/article/17/6/getting-started-go)，同时让 C 程序员感觉熟悉，但避免了 C 编程语言的许多常见陷阱。


本文比较了一个简单的 C 和 Go 程序，该程序将数字从一相加到十。由于这个程序只使用了小的数值，所以结果不会变得太大，因此只使用了普通的整数变量。像这样的循环在编程中非常常见，所以这个简单的程序很容易比较 C 和 Go。


### 如何在 C 中执行循环


C 语言中最基本的循环是 `for` 循环，它允许你对一组值进行迭代。`for` 循环的基本语法是：



```
for (起始条件 ; 结束条件 ; 每次迭代后执行的操作) { 循环内要执行的内容 ; }

```

你可以编写一个 `for` 循环，以打印从 1 到 10 的数字，将起始条件设置为 `count = 1`，将结束条件设置为 `count <= 10`。这样就以 `count` 变量等于 1 时开始循环。结束条件意味着只要 `count` 变量小于或等于 10 ，循环就会继续。


每次迭代之后，你使用 `count = count + 1` 将 `count` 变量的值增加 1。在循环内部，你可以使用 `printf` 打印 `count` 变量的值：



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

```

C 程序中常见的惯例是 `++`，它表示 “将某个值加一”。如果你写 `count++`，那就相当于 `count = count + 1`。大多数 C 程序员会使用 `count++` 来编写 `for` 循环中每次迭代后要执行的操作，像这样：



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

```

这是一个示例程序，将从 1 到 10 的数字相加，然后打印结果。使用 `for` 循环对数字进行迭代，但不要打印数字，而是将数字添加到 `sum` 变量中：



```
#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;
  }

```

这个程序使用了两个不同的 C 函数来向用户打印结果。`puts` 函数打印引号中的字符串。如果你需要打印纯文本，使用 `puts` 是个不错的选择。


`printf` [函数](https://www.redhat.com/sysadmin/command-basics-printf?intcmp=7013a000002qLH8AAM) 使用特殊字符在格式字符串中打印格式化的输出。`printf` 函数可以打印许多不同种类的值。关键字 `%d` 打印十进制（整数）值。


如果你编译并运行这个程序，你会看到这个输出：



```
adding 1 to 10 ..
The sum is 55

```

### 如何在 Go 中执行循环


Go 提供了与 C 中非常相似的 `for` 循环。C 程序中的 `for` 循环可以直接转换为 Go 的 `for` 循环，并具有相似的表示形式：



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

```

使用这个循环，你可以直接转换为 Go 的示例程序：



```
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)
}

```

虽然上述方式在 Go 中是正确的，但它并不是最常用的 Go 写法。采用惯例是“使用与本地语言为人所知的表达方式”。任何语言的目标都是高效的沟通，编程语言也不例外。在不同的编程语言之间进行转换时，重要的是意识到尽管物似而意不同，一种编程语言中的典型写法在另一种编程语言中可能不完全相同。


为使用更符合惯例的 Go，你可以进行几个小修改：


* 通过使用 `+=` 操作符来将 `sum = sum + count` 更简洁地表达为 `sum += count`。
* 通过使用 [分配并推断类型运算符](https://go.dev/ref/spec#Short_variable_declarations) 来表达 `count := 1` 而不是 `var count int` 跟着 `count = 1`。`:=` 语法同时定义并初始化 `count` 变量。
* 将 `count` 的声明移到 `for` 循环的头中。这减少了一些认知负担，也通过减少程序员在任何时候都必须心里记着的变量数目来提高可读性。这个更改还通过在最接近其使用的地方和最小的范围中声明变量来增加安全性，从而减少了在代码不断演进的过程中对变量进行意外操作的可能性。


上述改动的组合将产生以下代码：



```
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)
}

```

你可以使用这个 Go.dev 的 [链接](https://go.dev/play/p/pt5mfRDR0rh) 在 Go 试验场中尝试这个示例程序。


### C 和 Go 相似但不同


通过在两种编程语言中编写相同的程序，你可以看到 C 和 Go 这两种语言虽然相似但仍然不同。将从 C 转换到 Go 时需要注意以下几点：


* 在 C 中，每个程序指令都必须以分号结尾。这告诉编译器一个语句在哪里结束，下一个在哪里开始。在 Go 中，分号是有效的，但几乎总是可以推断出来。
* 虽然大多数现代 C 编译器会为你将变量初始化为零值，但 C 语言规范指出，变量得到的是内存中的任意值。Go 值总是初始化为其零值。这有助于使 Go 成为一种更具内存安全的语言。这种差异在使用指针时变得更加有趣。
* 注意 Go 程序包对导入标识符的使用方式。例如，`fmt` 是一个实现格式化输入和输出的函数，类似于 C 中的 `stdio.h` 中的 `printf` 和 `scanf`。`fmt` 程序包在 [pkg.go.dev/fmt](https://pkg.go.dev/fmt) 中有文档描述。
* 在 Go 中，`main` 函数总是以退出代码 0 返回。如果你希望返回其他值，你必须调用 `os.Exit(n)`，其中 `n` 通常为 1 以表示错误。这可以从任何地方调用，不仅仅是 `main` 函数，来终止程序。你可以在 C 中使用在 `stdlib.h` 中定义的 `exit(n)` 函数来实现相同的效果。


*（题图：MJ/8f731484-2dc3-4bac-b895-cbc92a63b48b）*




---


via: <https://opensource.com/article/23/4/c-vs-go-programming-languages>


作者：[Jim Hall](https://opensource.com/users/jim-hall) 选题：[lkxed](https://github.com/lkxed/) 译者：ChatGPT 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
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](https://opensource.com/article/17/6/getting-started-go) 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](https://www.redhat.com/sysadmin/command-basics-printf?intcmp=7013a000002qLH8AAM) 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](https://go.dev/ref/spec#Short_variable_declarations)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](https://go.dev/play/p/pt5mfRDR0rh).


## 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](https://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`

.

## Comments are closed.