表达式必须有常值问题

art*_*kin 0 c compiler-errors visual-studio constant-expression variable-length-array

我在 Visual Studio 中使用 C 编写了一个代码,供用户输入数组的大小。

该代码无法在 Visual Studio 中运行并给出错误。

但在像 replit 这样的网站上它是有效的。

我不明白如何才能使其在 Visual Studio 中工作。

在此输入图像描述

#include <stdio.h>
#include <time.h>
#include <string.h>
#include <math.h>

int main()
{
    int m;
    do
    {
        printf("please enter array size--> ");
        scanf_s("%d", &m);
    } while (m <= 1);

    int arry[m];

    for (int i = 0 + 1; i < m + 1; i++)
    {
        printf("%d,", arry[i] = i);
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Lun*_*din 6

您可以尝试下面的健全性检查代码来测试编译器的实用性和标准合规性:

#include <stdio.h>

int main()
{
  #if !defined(__STDC__) || !defined(__STDC_VERSION__)
    puts("This compiler is garbage.");
  #elif (__STDC_VERSION__ >= 201112L)
     #if (__STDC_NO_VLA__==1)
       puts("This compiler is mighty strange but compliant.");
     #else
       puts("This compiler is modern and useful.");
       int m = 5;
       int array[m];
     #endif
  #elif (__STDC_VERSION__ == 199901L)
    puts("This compiler is old but useful.");
    int m = 5;
    int array[m];
  #endif

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果编译器完全支持 C 语言,则输出“非常奇怪”或“垃圾”将不支持可变长度数组。

下面是各种常见 x86 编译器的输出。

默认设置

  • 铿锵 14.0.0 x86:This compiler is modern and useful.
  • 海湾合作委员会 12.1 x86:This compiler is modern and useful.
  • 国际ICC 2021.5.0 x86:This compiler is modern and useful.
  • icx 2022.0.0 x86:This compiler is modern and useful.
  • MSVC 19.32 x86:This compiler is garbage.

-std=c99

  • 铿锵 14.0.0 x86 -std=c99This compiler is old but useful.
  • 海湾合作委员会 12.1 x86 -std=c99This compiler is old but useful.
  • 国际商会 2021.5.0 x86: -std=c99:This compiler is old but useful.
  • icx 2022.0.0 x86 -std=c99::This compiler is old but useful.
  • MSVC 19.32 x86 /std:c99This compiler is garbage.

-std=c11

  • 铿锵 14.0.0 x86 -std=c11This compiler is modern and useful.
  • 海湾合作委员会 12.1 x86 -std=c11This compiler is modern and useful.
  • 国际ICC 2021.5.0 x86 -std=c11This compiler is modern and useful.
  • icx 2022.0.0 x86 -std=c11This compiler is modern and useful.
  • MSVC 19.32 x86 /std:c11This compiler is garbage.

-std=c17

  • 铿锵 14.0.0 x86 -std=c17This compiler is modern and useful.
  • 海湾合作委员会 12.1 x86 -std=c17This compiler is modern and useful.
  • 国际ICC 2021.5.0 x86 -std=c17This compiler is modern and useful.
  • icx 2022.0.0 x86 -std=c17This compiler is modern and useful.
  • MSVC 19.32 x86 /std:c17This compiler is garbage.