0
#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!

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • 5
    not true it works as a charm returns 256 https://onlinegdb.com/0mVb8VhEy – Giogre Jul 28 '22 at 22:13
  • 4
    Always fully bracket your macros, `#define C (1<<(8*1))`. Always, always, always. – Paul Sanders Jul 28 '22 at 22:17
  • 8
    Your claim that it prints "18" implies you tried `cout << C` and _not_ the code actually shown in your question. The macro would expand as `cout << 1 << 8`. Do you see the problem? Please ensure that when you ask a question about a behavior, you support it with _the code that causes that behavior_. – paddy Jul 28 '22 at 22:17
  • Unrelated to your question, but a nice reading: [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Yksisarvinen Jul 28 '22 at 22:21

1 Answers1

7

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
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52