问题描述
#define MAX 265
std::cout << 0 * MAX << std::endl; //to my surprise, the output is 9 rather than 0
这个C ++宏乘法?
EDIT :
以下是完整版本。
#include <stdio.h>
#include <string.h>
#include <iostream>
#define NAME_BYTES 256
#define VERSION_BYTES 256
#define SIZE_BYTES 32
#define USED_LOCK_COUNT_BYTES 32
#define LOCK_NAME_BYTES 256
#define LOCK_TYPE_BYTES 1
#define PID_BYTES 4
#define TID_BYTES 4
#define LOCK_BYTES LOCK_NAME_BYTES + LOCK_TYPE_BYTES + PID_BYTES + TID_BYTES
#define HEADER_BYTES NAME_BYTES + VERSION_BYTES + SIZE_BYTES + USED_LOCK_COUNT_BYTES
int main() {
std::cout << "LOCK_BYTES: " << LOCK_BYTES << std::endl;
std::cout << "HEADER_BYTES: " << HEADER_BYTES << std::endl;
std::cout << "LOCK_BYTES * 0: " << 0 * LOCK_BYTES << std::endl;
}
这是我刚才得到的结果和编译器信息。
Here's the result I just got and the compiler info.
yifeng @ yifeng-Precision-WorkStation-T3400:〜/ Shared- / examples / IMPL $
./a.out LOCK_BYTES:265 HEADER_BYTES:576 LOCK_BYTES * 0:9
yifeng@yifeng-Precision-WorkStation-T3400:~/Shared-Memory-Solution/examples/IMPL$ ./a.out LOCK_BYTES: 265 HEADER_BYTES: 576 LOCK_BYTES * 0: 9
编辑:谢谢你们这么多人!我一直很高兴,我决定发布,虽然我得到这么多downvote。
EDIT: Thank you so much guys!! I've been most happy that I decided to post this, although I am getting so many downvotes. What a lesson to learn about MACRO!
推荐答案
您应该始终在宏定义的后面加上括号:
You should always put parentheses around macro definitions:
#define LOCK_BYTES (LOCK_NAME_BYTES + LOCK_TYPE_BYTES + PID_BYTES + TID_BYTES)
否则,代码会扩展为:
cout << 0 * LOCK_NAME_BYTES + LOCK_TYPE_BYTES + PID_BYTES + TID_BYTES
输出 LOCK_TYPE_BYTES + PID_BYTES + TID_BYTES
。
更好的是,不要使用宏,除非你真的需要。这些更好地表示为常量变量。
Better still, don't use macros unless you really have to. These are better represented as constant variables.
这篇关于C ++宏乘法发生了什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!