2

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!

1
  • Look at the preprocessing output (I took out the using directive because no std namespace exists in your code). Commented Mar 18, 2014 at 2:39

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

May you could explain: (1) which semicolons, (2) why should we not end those lines with such?
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.