2

I have a program where I get the error:

variable modified 'artikel' at file scope
char artikel[ARTNAME];

I think I have to add a #define, but exactly which one should it be?

Here is my code:

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

const int ARTNAME = 100;

typedef struct artikel {
    char artikel[ARTNAME];
    int anzahl;
} artikel;

int main()
{
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
flavio
  • 21
  • 1
  • 1
    `#define ARTNAME 100`. [variably modified array at file scope in C](https://stackoverflow.com/q/13645936) – 001 Dec 29 '20 at 13:55
  • i add #define ARTNAME 100 and now it gives me out----> main.c:5:20: error: expected identifier or ‘(’ before numeric constant #define ARTNAME 100 – flavio Dec 29 '20 at 13:57
  • 1
    Cannot reproduce: https://godbolt.org/z/1Mo69q – 001 Dec 29 '20 at 13:58
  • To compile this code, as is, you can turn on a `C99` or above standard. It will not pass in older `C` standards. – user14063792468 Dec 29 '20 at 13:58
  • ok thanks, i will try it – flavio Dec 29 '20 at 14:02
  • 1
    @flavio, you do not *add* the `#define`. You *change* the existing declaration of `ARTNAME` into a `#define`. – John Bollinger Dec 29 '20 at 14:08
  • 2
    Does this answer your question? [Variably modified array at file scope in C](https://stackoverflow.com/questions/13645936/variably-modified-array-at-file-scope-in-c) – Toby Speight Jul 29 '23 at 12:08
  • You will have to wait for C23 to have a C++ like `constexpr`. Otherwise `const int ARTNAME` is a variable, not literal constant. It's use in declaring `char artikel[ARTNAME];` results in a VLA. `#define ARTNAME 100` requires no storage space -- it is simply a compile-time substitution. `const int ARTNAME = 100;` is a *definition* of the variable `ARTNAME` and requires storage in your program. The subtle resulting difference is you cannot use a `#define` where you need the address of the variable later (it simply doesn't exist) – David C. Rankin Aug 14 '23 at 21:50

1 Answers1

2

I have a program where I get the error: variable modified 'artikel'at file scope char artikel[ARTNAME];

I don't think you have copied the diagnostic accurately. It is surely complaining about struct artikel being variably modified.

That is closely related to the issue covered in Variably modified array at file scope in C. Specifically, const qualification notwithstanding, ARTNAME is not a "constant expression" in C, so the type of array artikel.artikel and therefore also of the whole struct artikel are "variably modified". Objects with variably modified types cannot be declared at file scope.

I think I have to add a #define, but I don't understand exactly which one.

The quickest solution would probably be to change this ...

    const int ARTNAME = 100;

... to:

#define ARTNAME 100
John Bollinger
  • 160,171
  • 8
  • 81
  • 157