noizybrain
noizybrain

Reputation: 155

Using Constants to Set Array Size in C++

I saw a similar question on here but the answer seemed to match what I already have.

#define POP_SIZE 10;
#define GENE_SIZE 24;

using namespace std;

int main()
{
    char population[POP_SIZE][GENE_SIZE];
    return 0;
}

The compiler gives me the error "Expected ']'" and "Expected expression". I'm using Xcode 5. Probably a dumb question, but thanks for helping!

Upvotes: 2

Views: 96

Answers (3)

shawn1874
shawn1874

Reputation: 1425

I have a better idea. How about "const int POP_SIZE 10;" and "const int GENE_SIZE 10;"? There are many other situations that will cause strange compiler errors because of the text substitutions. Always prefer scoped constants over #define statements.

I speak from years of experience, and I have had to maintain code within large scale projects with even bigger problems than that due to inappropriate use of preprocessor statements. Macros have uses, but there is really no good reason to write constants like that. It is better to break the habit now, rather than spend hours studying compiler errors that make no sense.

Upvotes: 0

4pie0
4pie0

Reputation: 29724

Remove semicolons:

#define POP_SIZE 10
                   ^  // no semicolon
#define GENE_SIZE 24
                    ^ // no semicolon

using namespace std;

int main()
{
    char population[POP_SIZE][GENE_SIZE];
    return 0;
}

The #define a b directive has such an effect that what text b turns out to be, is just substituted in each occurrence of a in a program. This is why it is expanded to

int main()
{
    char population[10;][24;];
    return 0;
}

which is an error. Clang flag -E can be added to compilation command to visualize expanded code, i.e:

clang++ -E -std=c++1y -O3 -Wall -Wextra -pedantic-errors main.cpp && ./a.out

Upvotes: 5

Guilherme
Guilherme

Reputation: 453

As Lizusek says, just remove the semicolon from #define. The macro #define is just text. So, when you put a semicolon in the end, the compiler will replace all the macro text by your constant and a semicolon.

int main()
{
    char population[10;][24;];
    return 0;
}

That's why you are getting a compile error.

Upvotes: 1

Related Questions