这在C语言中有效吗?
#include <stdio.h>
int main()
{
int i = 5;
int a[i]; // Compiler doesn't give error here. Why?
printf("%d",sizeof(a)); //prints 5 * 4 =20. 4 is the size of integer datatype.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器不会在声明中给出错误int a[i];.我不是一个常数,那么它怎么能成功编译?是因为我使用的是gcc编译器吗?是否允许在C++中使用?
#include <stdio.h>
void main()
{
int x = 99;
int y = sizeof(x++);
printf("x is %d", x);
}
Run Code Online (Sandbox Code Playgroud)
以上程序的结果是:
x是99
为什么?任何人都可以告诉为什么sizeof运算符x不会增加.
我在想象下面的场景:从一个空向量开始,向它推送一些int,然后使用它的大小来声明一个内置数组.
vector<int> vec; /* default init'ed */
for(decltype(vec.size()) i = 0; i != 10; ++i){
vec.push_back(i);
}
constexpr size_t sz = vec.size();
int arr[sz] = {}; /* list init, left out elem's are 0 */
Run Code Online (Sandbox Code Playgroud)
这个程序对我来说很直观(作为初学者).但它失败了以下消息:
testconstexpr2.cpp:22:34: error: call to non-constexpr function ‘std::vector<_Tp, _Alloc>::size_type std::vector<_Tp, _Alloc>::size() const [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
testconstexpr2.cpp:23:13: error: size of array ‘arr’ is not an integral constant-expression
Run Code Online (Sandbox Code Playgroud)
我宁愿坚持使用内置数组,然后再去处理std :: array或dynamic array alloc.
我读到需要在编译时知道数组大小.但是,当我这样做时,它编译并运行得很好,没有任何错误......怎么样?
#include <iostream>
int main() {
int size;
std::cout << "Enter size: ";
std::cin >> size;
int a[size];
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我只是想知道是否const int N=10会在编译时执行句子.我问的原因是因为以下代码将起作用.
int main()
{
const int N=10;
int a[N]={};
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是这个不会.
int main()
{
int N=10;
int a[N]={};
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我遇到了错误,其中VLA的声明给出了"表达式没有评估为常量"的错误 - 我试图声明int l,m,r,n1,n2常量,但它仍然不起作用.虽然我知道编译器想要在编译时知道固定大小数组的概念,但是我看到很少有在线实现,人们已经实现如下.
其他wiki搜索输入链接描述这里 显示并非所有版本的C++都支持它 -
问题 - 如何在不创建动态内存分配的情况下使其工作?
template<typename T>
void mergesort<T>::_merge_array(int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2]; // error -
}
Run Code Online (Sandbox Code Playgroud) 我正在慢慢将自己升级到c ++ 11.我看着constexpr并偶然发现这篇维基百科文章引导我"完全不同的东西".它给出的基本例子是:
int get_five() {return 5;}
int some_value[get_five() + 7]; // Create an array of 12 integers. Ill-formed C++
Run Code Online (Sandbox Code Playgroud)
它声明"这在C++ 03中不合法,因为get_five()+ 7不是常量表达式." 并说,加入constexpr该get_five()声明解决了这个问题.
我的问题是"有什么问题?".我编译的代码既没有错误也没有警告.我玩它使它非常不稳定:
#include <iostream>
int size(int x) { return x; }
int main()
{
int v[size(5) + 5];
std::cout << sizeof(v) + 2 << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
使用以下内容编译时没有任何投诉:
g++ -Wall -std=c++03
Run Code Online (Sandbox Code Playgroud)
并且在执行时我得到(正确的)答案42.
我承认我通常使用stl容器,而不是数组.但我认为(显然维基百科也是这样)上述代码的编译会失败.它为什么成功?