English 中文(简体)
在C++中,为什么在我以价值通过时,把固定的复印件拖到另一个固定的状态?
原标题:In C++, why doesn t the copy of a constant also have to be a constant when I pass it by value?

For example, this code compiles (g++ 13.1.0) and gives me output "Sum is 20":

#include <iostream>

using namespace std;

void add (int x, int y, int sum);

int main(){
    int x = 10, y = 10;
    const int sum = 0;

    add (x, y, sum);

    return 0;
}

void add (int x, int y, int sum) {
    sum = x + y;
    cout << "Sum is " << sum << endl;
}

我期望汇编者抱怨,要么试图将固定价值传递给在职能范围内被视为非同寻常的东西,要么没有宣布<代码>sum为add。 我认为,我理解这里发生的一切——我造就一个固定变量的非固定副本。 我很奇怪,为什么允许这种行为。

问题回答

在C++中,为什么在我以价值通过时,把固定的复制件拖到另一个不变的状态?

由于在C++中,变数是否一致,在宣布/界定该变量时即终止

尤其是,当你写了<代码>int x时,你特别说,你不想打上<代码>x<>/code>。 如果您希望<条码>x成为星号,则声明将包含一个星号,载于<条码>const int x。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?