初始化与赋值不同吗? [英] Initialization different from assignment?

查看:80
本文介绍了初始化与赋值不同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1.char str[] = "hello"; //legal  

2.char str1[];
str1 = "hello"; // illegal

我知道"hello"从字符串文字池返回字符串文字的地址,该地址不能直接分配给数组变量.在第一种情况下,"hello"文字中的字符被逐个复制到数组中,并在末尾添加"\ 0".

I understand that "hello" returns the address of the string literal from the string literal pool which cannot be directly assigned to an array variable. And in the first case the characters from the "hello" literal are copied one by one into the array with a '\0' added at the end.

这是因为赋值运算符"="在此过载以支持此操作吗?

Is this because the assignment operator "=" is overloaded here to support this?

我还想知道初始化与赋值不同的其他有趣情况.

I would also like to know other interesting cases wherein initialization is different from assignment.

推荐答案

不能 将其视为重载(无论如何在C中都不存在),因为用字符串文字初始化char数组是一种特殊情况.字符串文字的类型为const char[N],因此,如果它类似于重载,则可以使用类型为const char[N]的任何表达式来初始化char数组.但是你不能!

You cannot think of it as overloading (which doesn't exist in C anyway), because the initialization of char arrays with string literals is a special case. The type of a string literal is const char[N], so if it were similar to overloading, you'd be able to initialize a char array with any expression whose type is const char[N]. But you cannot!

const char arr[3];
const char arr1[] = arr; //compiler error. Cannot initialize array with another array.

语言标准只是说可以使用字符串文字初始化字符数组.由于他们对分配一事无成,因此一般规则尤其适用于无法分配数组的情况.

The language standard simply says that character arrays can be initialized with string literals. Since they say nothing about assignment, the general rules apply, in particular, that an array cannot be assigned to.

对于初始化不同于赋值的其他情况:在C ++中,存在引用和类,其中将有无数的示例.在C中,没有完整的类或引用,我想到的唯一一件事就是const变量:

As for other cases when initialization is different from assignment: in C++, where there are references and classes, there would be zillions of examples. In C, with no full-fledged classes or references, the only other thing I can think of off the top of my head is const variables:

const int a = 4; //OK;
const int b; //Error;
b = 4; //Error;

另一个例子:带有大括号的数组初始化

Another example: array initialization with braces

int a[3] = {1,2,3}; //OK
int b[3];
b = {1,2,3}; //error

与结构相同

这篇关于初始化与赋值不同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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