2

Consider:

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

const int STRING_SIZE = 40;
typedef char string[STRING_SIZE];

char typeInput(string message);

int main()
{
    typeInput("Hi my name is Sean");
}

char typeInput(string message)
{
    printf(" %s", message);
}

Error:

error: variably modified 'string' at file scope

I keep getting this error for some reason. Where did I go wrong?

Just in case, I'm using Code::Blocks.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sean Ervinson
  • 123
  • 3
  • 12
  • I named the char variable "string" – Sean Ervinson Oct 22 '16 at 16:57
  • Wait what do you mean (noob programmer) – Sean Ervinson Oct 22 '16 at 17:01
  • `const int STRING_SIZE = 40;` --> `#define STRING_SIZE 40`. Also Change type of return of `typeInput` to `void` from `char`. – BLUEPIXY Oct 22 '16 at 19:02
  • http://stackoverflow.com/questions/1712592/variably-modified-array-at-file-scope – melpomene Oct 22 '16 at 22:32
  • @melpomene: No, that is for [Objective-C](https://en.wikipedia.org/wiki/Objective-C), not [C](https://en.wikipedia.org/wiki/C_%28programming_language%29) – Peter Mortensen Jul 29 '23 at 11:28
  • Possible duplicate: *[Variably modified array at file scope in C](https://stackoverflow.com/questions/13645936/variably-modified-array-at-file-scope-in-c)* (see also [the linked questions](https://stackoverflow.com/questions/linked/13645936)). – Peter Mortensen Jul 29 '23 at 11:29
  • 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:07

1 Answers1

4

In C, const doesn't declare a constant, it declares a read-only variable. The compiler complains because STRING_SIZE is not a constant.

Workaround:

enum { STRING_SIZE = 40 };
// enum creates constants in C (but only integer ones)
melpomene
  • 84,125
  • 8
  • 85
  • 148