msc*_*msc 63 c++ arrays pointers unary-operator
我在这里看到了一种奇怪的程序.
int main()
{
int s[]={3,6,9,12,18};
int* p=+s;
}
Run Code Online (Sandbox Code Playgroud)
上面的程序在GCC和Clang编译器上进行了测试,并在两个编译器上都运行良好.
我很想知道,int* p=+s;
做了什么?
数组是否已s
衰减为指针类型?
son*_*yao 63
内置operator+
可以将指针类型作为其操作数,因此将数组传递s
给它会导致数组到指针的转换,然后int*
返回指针.这意味着你可以+s
单独使用来获取指针.(对于这种情况,它是多余的;没有operator+
它也会衰减到指针,然后分配给p
.)
(强调我的)
内置的一元加运算符返回其操作数的值.它不是no-op的唯一情况是当操作数具有整数类型或未整合的枚举类型时,它由整数提升改变,例如,它将char转换为int或者如果操作数受到左值到右值的影响,数组到指针或函数到指针的转换.
Khu*_*dov 25
测试一下:
#include <stdio.h>
int main(){
char s[] = { 'h', 'e', 'l', 'l', 'o' , ' ', 'w', 'o', 'r', 'l', 'd', '!'} ;
printf("sizeof(s) : %zu, sizeof(+s) : %zu\n", sizeof(s), sizeof(+s) ) ;
}
Run Code Online (Sandbox Code Playgroud)
在我的电脑(Ubuntu x86-64)上打印:
sizeof(s): 12, sizeof(+s) : 8
Run Code Online (Sandbox Code Playgroud)
哪里
12 = number of elements s times size of char, or size of whole array
8 = size of pointer
Run Code Online (Sandbox Code Playgroud)
tas*_*oor 11
这是一个一元加号,在这里没有实际效果.例如:
#include <iostream>
int main() {
int a[] = {1};
std::cout << a << " " << +a << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
这将打印两个a
和相同的地址+a
.数组像往常一样衰减到指针.
请注意,如果它是一元减号,-a
那么GCC会显示错误:
error: wrong type argument to unary minus
Run Code Online (Sandbox Code Playgroud)
编辑:虽然它具有OP的代码没有任何影响,a
而且+a
是不完全一样的.有关详细信息,请参阅Khurshid Normuradov和songyuanyao的答案.