I was recently given a list of possible C++ interview questions by a recruiter for a firm on Wall St. One of the questions was:


How would you generate a compile time error if the sizeof(int) is not equal to 4?

I was thinking along the lines of template specialization or some such thing, but I'm not sure. Any ideas?

Thanks.

-Marc

Recommended Answers

All 5 Replies

You can do it with templates, but it really isn't a better approach complexity-wise. The common method is to use the preprocessor with <climits>:

#include <climits>
#include <iostream>

#if INT_MAX != 2147483647
#  error integers must be 32 bits long
#endif

int main ( void )
{
  std::cout<< INT_MAX <<std::endl;

  return 0;
}

Though you need to be careful because the calculation might make an unwarranted assumption as above, such as CHAR_BIT being 8. Sometimes the assumption is safe, other times it constitutes an error.

How about this?

#include <stdio.h>

char dummy [ sizeof(int) == 4 ];

int main(void)
{
   return 0;
}

>How about this?
Cute, but it's not very informative, is it? ;) Though you do meet the requirements for the question. I wish I had remembered that trick for my reply, it's cleaner.

You can do it with templates, but it really isn't a better approach complexity-wise.

Could you demonstrate the template based way to do this? I can't seem to figure this out. Thanks!

>Could you demonstrate the template based way to do this?

template <bool>
struct static_assert;

template <>
struct static_assert<true> {
};

int main()
{
  static_assert<sizeof ( int ) == 4>();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.