循环在此代码中只迭代一次,而在另一个代码中,它会正确迭代

时间:2017-03-31 10:24:32

标签: c++ arrays loops sizeof

为什么循环在此代码中只运行一次?

 // Example program
    #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
    int n=5;
    int a[n];
    for(int i=0;i<sizeof(a);i++)
    {
        cout<<"mohit jain"<<endl;
    }
      return 0;
    }

在代码中循环迭代五次?

// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a[5];
for(int i=0;i<sizeof(a);i++)
{
    cout<<"mohit jain"<<endl;
}
  return 0;
}

所以请告诉我为什么它在第一个代码中迭代一次,而在第二个代码中迭代五次。

1 个答案:

答案 0 :(得分:2)

请考虑使用const int n = 5。 默认情况下,C ++不允许使用动态大小的数组(在这种情况下,它是动态的,因为n是非常量的)。它的工作原理只是因为你的编译器在这种情况下使用某种扩展来分配一个数组,例如gcc的变量数组。

因此,第一个示例是非标准C ++代码,sizeof返回1而不是5 * sizeof(int)的原因在于扩展的特定于编译器的实现。

顺便说一句,第二个循环运行5 * sizeof(int)次(在大多数系统上运行20次),而不是5次。

相关问题