Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to drive C#, C++ or Java compiler to compute 1+2+3+...+1000 at compile time?
    text
    copied!<p>In a recent interview, I was asked a really strange question. The interviewer asked me how can I compute 1+2+3+...+1000 just using compiler features. This means that I am not allowed to write a program and execute it, but I should just write a program that could drive the compiler to compute this sum while compilation and print the result when compilation completes. As a hint, he told me that I may use generics and pre-processor features of the compiler. It is possible to use C++, C# or Java compiler. Any ideas???</p> <p>This question is not related to computing the sum without any loops <a href="https://stackoverflow.com/questions/4568645/printing-1-to-1000-without-loop-or-conditionals/4568650#4568650">asked here</a>. In addition, It should be noted that the sum SHOULD be calculated during compilation. Printing just the result using C++ compiler directives is not acceptable. </p> <hr> <p>Reading more about the posted answers, I found that solving problems during compilation using C++ templates is called <strong>metaprogramming</strong>. This is a technique that was discovered accidentally by Dr. Erwin Unruh, during the process of standardizing the C++ language. You may read more about this topic on <a href="http://en.wikipedia.org/wiki/Template_metaprogramming" rel="nofollow noreferrer">wiki page of meta-programming</a>. It seems that it is possible to write the program in Java using java annotations. You may take a look at <strong><a href="https://stackoverflow.com/a/8815298/114029">maress's</a></strong> answer below. </p> <p>A nice book about meta-programming in C++ is <a href="http://rads.stackoverflow.com/amzn/click/0201704315" rel="nofollow noreferrer">this one</a>. Worth to take a look if interested. </p> <p>A useful C++ meta-programming library is Boost's MPL <a href="http://www.boost.org/doc/libs/1_58_0/libs/mpl/doc/index.html" rel="nofollow noreferrer">this link</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload