#include<iostream>
using namespace std;
#define C 1<<(8*1)
int main(){
if(C==256){
int a=C;
cout<<a;
}
}
My expectation is 256 but it print 18. What's wrong with it? Thanks!
I assume your question is about std::cout << C;
, not about std::cout << a;
.
Macros are simple copy-and-paste text replacement. When preprocessor encounters macro name, it replaces it with the definition as text without any analysis. So, what happens is that
std::cout << C;
is replaced with
std::cout << 1<<(8*1);
which should indeed print 18
.
That's one very good reason to not use macros. Instead, use a constant (or constexpr) variable:
constexpr int C = 1 << (8 * 1);
This is type safe and will never surprise you when used in any context.
If you really have to use macro for some reason, make sure to wrap it in extra parantheses:
#define C (1 << (8 * 1)) // but seriously, don't use macros