-4

I'm trying to define 'N' to be the number of chars in my class, by putting #define N 10 at the beginning of my .h file, when i do that i get a lot of errors including missing (, missing ) missing ] etc.

this is my code:

#define N 10;

class String
{
private:
    char str[N];
public:
    String();
    String(char[]);
    ~String();
};

When i change it to

    char str[10];

it does work, isn't it supposed to be the same?

Thanks.

argamanza
  • 1,122
  • 3
  • 14
  • 36

4 Answers4

7
#define N 10;
//          ^

So char str[N]; becomes

char str[10;];
//         ^

Remember that the preprocessor just does its job of replacing what you specify for a macro. You specified 10; so it inserts 10; for N.

A better solution than to remove that pesky ; is to do something like this1

class String
{
private:
    static const int numChars = 10;
    char str[numChars];
public:
    String();
    String(char[]);
    ~String();
};

Great chances are you will not need to have the N in other parts of your code other than String, so why not just define something better inside String? "something better" because of the general notion that macros are evil and thus not using macros makes you, well, not evil (or at least, lesser evil).

1 You should note of this: Defining static const integer members in class definition

Community
  • 1
  • 1
Mark Garcia
  • 17,424
  • 4
  • 58
  • 94
1
#define N 10;

The ; at the end is causing problems. Remove it.

#define N 10
Sakthi Kumar
  • 3,047
  • 15
  • 28
1

#define N 10; should be #define N 10

Jarod42
  • 203,559
  • 14
  • 181
  • 302
1

If you don't want to use a magic number in the class and put it outside, #define is not the best way as it has a global effect, that is everywhere that N appears anywhere in the code it will be replaced by 10. You probably want to localise it.

You can do that in a namespace and const size_t declaration within that namespace.

namespace MyModule {
   const size_t STRING_ARRAY_SIZE = 10; // you do want the semi-colon
}

class String
{
 private:
     char str[ MyModule::STRING_ARRAY_SIZE ]; 
       // rest of class
};

If the class String is in the namespace MyModule you do not need to qualify with :: within the class. If you want the size limited to within the class you can put it there.

Note that no matter where you put it and how it is defined it must be a compile-time constant. It is not something you can store in configuration as the array size must be known at compile time as sizeof(String) depends on it.

Incidentally, Strings are commonly implemented with a static array for short strings and a dynamic one for longer strings. For non-mutable strings one will sometimes implement the long strings with some "shared" array. It can make swap() difficult to implement but it can be more efficient with fewer dynamic allocations.

Your constructor taking char[] is not a good idea really. Probably should take const char *.

CashCow
  • 30,981
  • 5
  • 61
  • 92