Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cout macro value doesn't work as expected

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading