C 甚至有“通过引用传递"吗? [英] Does C even have "pass by reference"?

查看:52
本文介绍了C 甚至有“通过引用传递"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说在c"中,我们可以通过按值调用"或按引用调用"传递参数.但是在一本书中提到,我们可以通过两种方式传递参数,但没有通过引用传递",但实际上我通过通过引用传递"传递了大部分参数.

I heard that in "c" that there are we can pass the arguments via "call by value" or "call by reference". But in one book it's mentioned that there are we can pass the arguments via both way but there is no "pass by reference" but I actually pass the mostly arguments by "pass by reference".

那么为什么会提到C 甚至有通过引用传递"?

So why it is mentioned "does C even have "pass by reference"?

详细描述将不胜感激.

推荐答案

C 参数总是按值传递,而不是按引用传递.但是,如果您将对象的地址视为对该对象的引用,那么您可以按值传递该引用.例如:

C parameters are always passed by value rather than by reference. However, if you think of the address of an object as being a reference to that object then you can pass that reference by value. For example:

void foo(int *x)
{
    *x = 666;
}

您在评论中提问:

当我们可以按值传递所有参数时,为什么我们需要在 C 中使用指针?

So why do we need pointers in C when we can pass all the parameters by value?

因为在仅支持按值传递的语言中,缺少指针将是一种限制.这意味着你不能写这样的函数:

Because in a language that only supports pass-by-value, lack of pointers would be limiting. It would mean that you could not write a function like this:

void swap(int *a, int *b)
{
    int temp = *a;
    *b = *a;
    *a = temp;
}

例如,在 Java 中,无法编写该函数,因为它只有按值传递而没有指针.

In Java for example, it is not possible to write that function because it only has pass-by-value and has no pointers.

在 C++ 中,您将使用如下引用编写函数:

In C++ you would write the function using references like this:

void swap(int &a, int &b)
{
    int temp = a;
    b = a;
    a = temp;
}

在 C# 中也类似:

void swap(ref int a, ref int b)
{
    int temp = a;
    b = a;
    a = temp;
}

这篇关于C 甚至有“通过引用传递"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆