[英]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
*的操作数必须是一个指针
You should not terminate the macro definitions with ;
您不应该使用
;
终止宏定义;
. 。 Otherwise the expression expands to:
否则,表达式将扩展为:
area=10;*WIDTH;
Now the error makes sense, right? 现在,错误才有意义,对吗?
#define LENGTH 10;
should be 应该
#define LENGTH 10
// ^ no trailing ;
At present, the preprocessor expands your code to 目前,预处理器将您的代码扩展到
area=10;*WIDTH;
// ^ error
Never, ever, terminate a macro with a semicolon. 永远不要以分号终止宏。
#define LENGTH 10
is what you need. 是您所需要的。
Macros are simple text replacements. 宏是简单的文本替换。
Your macro LENGTH
expands to the tokens 10;
您的宏
LENGTH
扩展为令牌10;
. 。
Then your statement in main
is actually two statements: 那么您的
main
语句实际上是两个语句:
area = LENGTH; *WIDTH
This attempts to dereference WIDTH
, which is not a pointer and therefore cannot be dereferenced. 这将尝试取消引用
WIDTH
,它不是指针,因此无法取消引用。
Your definition includes a semicolon which would normally end the statement. 您的定义包括一个分号,该分号通常会结束该语句。
#define LENGTH 10;
Remove the semicolon. 删除分号。
Exists error in your LENGTH macros, remove semicolon. 在您的LENGTH宏中存在错误,请删除分号。
Good: #define LENGTH 10
好:
#define LENGTH 10
Use the std::endl
for carriage return. 使用
std::endl
进行回车。
std::cout<< area << std::endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.