| | |
[Q] Generating compile time error when sizeof(int) != 4
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: Nov 2004
Posts: 2
Reputation:
Solved Threads: 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
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
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>:
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.
C++ Syntax (Toggle Plain Text)
#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; }
New members chased away this month: 4
>Could you demonstrate the template based way to do this?
C++ Syntax (Toggle Plain Text)
template <bool> struct static_assert; template <> struct static_assert<true> { }; int main() { static_assert<sizeof ( int ) == 4>(); }
New members chased away this month: 4
![]() |
Similar Threads
- Compile time error "undeclared identifier"for functions strcpy_s,strcat_s,_itoa_s (C++)
- system.NullReferenceException (C#)
Other Threads in the C++ Forum
- Previous Thread: wrong output in c program
- Next Thread: Draw a circle on a Windows form
| Thread Tools | Search this Thread |
Tag cloud for C++
api application array arrays based beginner binary bmp c++ c/c++ calculator char char* class classes code compile compiler console conversion convert count data delete deploy dll dynamiccharacterarray email encryption error file format forms fstream function functions game givemetehcodez graph gui homeworkhelp iamthwee ifstream input int java lib library lines list loop looping loops map math matrix memory newbie news number numbertoword output pointer problem program programming project python random read recursion recursive reference return rpg search simple sorting spoonfeeding string strings struct temperature template templates text text-file tree url variable vector video visual visualstudio void win32 windows winsock wordfrequency wxwidgets







Though you do meet the requirements for the question. I wish I had remembered that trick for my reply, it's cleaner.