CODError
CODError

Reputation: 779

C++ error when multiplying #define and const variable

#include <iostream>
#include<Windows.h>

#define LENGTH 10;
#define NEWLINE '\n'
using namespace std;

int main(){
    int area;
    const int WIDTH=20;
    area=LENGTH*WIDTH;   
    cout<<area<<NEWLINE;
    system("pause");
}

Error is at line where area is calculated, it says "

operand of * must be a pointer

Upvotes: 1

Views: 288

Answers (6)

fcennecf
fcennecf

Reputation: 213

Exists error in your LENGTH macros, remove semicolon.

Good: #define LENGTH 10

Use the std::endl for carriage return.

std::cout<< area << std::endl;

Upvotes: 0

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70969

You should not terminate the macro definitions with ;. Otherwise the expression expands to:

area=10;*WIDTH;

Now the error makes sense, right?

Upvotes: 8

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385224

Macros are simple text replacements.

Your macro LENGTH expands to the tokens 10;.

Then your statement in main is actually two statements:

area = LENGTH; *WIDTH

This attempts to dereference WIDTH, which is not a pointer and therefore cannot be dereferenced.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234745

Never, ever, terminate a macro with a semicolon.

#define LENGTH 10

is what you need.

Upvotes: 2

Brian Cain
Brian Cain

Reputation: 14619

Your definition includes a semicolon which would normally end the statement.

#define LENGTH 10;

Remove the semicolon.

Upvotes: 1

simonc
simonc

Reputation: 42175

#define LENGTH 10;

should be

#define LENGTH 10
//               ^ no trailing ;

At present, the preprocessor expands your code to

area=10;*WIDTH;
//     ^ error

Upvotes: 3

Related Questions