VScode "expression must have a constant value" in c99 mode

Viewed 463

What I'm trying to do:
I need to write integers into a 2d array. The length of the array is N*N. So I scanf to get the value of N from the user.

The C/C++ extension gives the "expression must have a constant value". But building it with gcc works perfectly fine

What I've tried:
C/C++ extension gives error on N in both arrays, "expression must have a constant value".

After some googling answers, I tried to set my compiler version in the extension to c99, since that is the version which supports variable length arrays. But it still give the same error. Tried using other newer c versions, the intellicense still gives the same error.

Code and settings:
tree.c:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int N, i, j;
    scanf("%d", &N);
    int min_tree[N][N];
    int tree_walked[N];
}

c_cpp_properties.json:

{
    "name": "TUF_Laptop",
    "includePath": [
        "${workspaceFolder}/**",
        "/usr/local/include",
        "/usr/include",
        "/usr/lib/gcc/x86_64-pc-linux-gnu/11.1.0/include",
        "/usr/lib/gcc/x86_64-pc-linux-gnu/11.1.0/include-fixed",
        "/usr/lib/gcc/x86_64-pc-linux-gnu"
    ],
    "defines": [
        "_DEBUG",
        "UNICODE",
        "_UNICODE"
    ],
    "compilerPath": "/usr/bin/gcc",
    "intelliSenseMode": "linux-gcc-x64",
    "compilerArgs": [
        "-O3 -Wall -Wextra -std=c99"
    ],
    "cStandard": "c99",
    "cppStandard": "gnu++17",
    "compileCommands": ""
}

Similar answers I found: "expression must have a constant value" error in VS code for C

2 Answers

The IDE may be warning you of a potential programming error, since value N can be changed while mintree and treewalked are still in scope. You should be able to fix this with the following modification:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int N_scan, i, j;
    scanf("%d", &N_scan);
    const int N = N_scan;
    int min_tree[N][N];
    int tree_walked[N];
}

The value of N cannot be changed while min_tree and tree_walked are in scope.

There is a similar answer (for a C++ case) here:

https://stackoverflow.com/questions/9219712/c-array-expression-must-have-a-constant-value#:~:text=expression%20must%20have%20a%20constant%20value.%20When%20creating,declared%20const%3A%20doesn%27t%20even%20provide%20a%20variable%20name.

Just to add to the other answer, VS Code's intellisense defaults to MSVC as compiler. MSVC does not support the entirety of C99 including non-constant length arrays.

You can change the compiler used in VS Code's settings and set it to GCC which supports this feature.

In vs code, type "C/C++: Edit Configurations (UI)" (without the quotes) in the command palette (Ctrl + Shift + P) and edit the configuration. It will however create a .vscode/c_cpp_properties.json file in your folder. I don't think there is a way to set it globally other than copying this file to every .vscode folder.

screenshot

Related