1,105,380 Community Members

[Q] Generating compile time error when sizeof(int) != 4

Member Avatar
mdos
Newbie Poster
2 posts since Nov 2004
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
Narue
Bad Cop
12,139 posts since Sep 2004
Reputation Points: 5,693 [?]
Q&As Helped to Solve: 1,537 [?]
Skill Endorsements: 81 [?]
Team Colleague
 
0
 

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.

Member Avatar
Dave Sinkula
long time no c
4,852 posts since Apr 2004
Reputation Points: 2,398 [?]
Q&As Helped to Solve: 340 [?]
Skill Endorsements: 69 [?]
Team Colleague
 
0
 

How about this?

#include <stdio.h>

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

int main(void)
{
   return 0;
}
Member Avatar
Narue
Bad Cop
12,139 posts since Sep 2004
Reputation Points: 5,693 [?]
Q&As Helped to Solve: 1,537 [?]
Skill Endorsements: 81 [?]
Team Colleague
 
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.

Member Avatar
mdos
Newbie Poster
2 posts since Nov 2004
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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!

Member Avatar
Narue
Bad Cop
12,139 posts since Sep 2004
Reputation Points: 5,693 [?]
Q&As Helped to Solve: 1,537 [?]
Skill Endorsements: 81 [?]
Team Colleague
 
0
 

>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>();
}
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article