Thread: compile time error or runtime error?

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    1,579

    compile time error or runtime error?

    Hello everyone,


    Could anyone let me know why compiler can not make runtime error report in the following code, other than throw cast exception during runtime?

    Code:
        static void Main()
        {
            int i = 100;
            object b = i;
            long l = (long)b; // why compiler can not make type check here?
    
            return;
        }

    thanks in advance,
    George

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Did you mean to say: "why compiler can not make compile time error report in the following code"?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Because b is an "object" which can be a "long" (which is valid cast) but also something else (which might be invalid cast). The compiler does not know, and far from all cases are as easy to detect as the one you show.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  4. #4
    Registered User
    Join Date
    May 2006
    Posts
    1,579
    Thanks laserlight and Magos,


    Are there any documents about why type cast/conversion are checked by C# compiler? :-)

    Quote Originally Posted by Magos View Post
    Because b is an "object" which can be a "long" (which is valid cast) but also something else (which might be invalid cast). The compiler does not know, and far from all cases are as easy to detect as the one you show.

    regards,
    George

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner Needs help in Dev-C++
    By Korrupt Lawz in forum C++ Programming
    Replies: 20
    Last Post: 09-28-2010, 01:17 AM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. ras.h errors
    By Trent_Easton in forum Windows Programming
    Replies: 8
    Last Post: 07-15-2005, 10:52 PM
  5. Linking error
    By DockyD in forum C++ Programming
    Replies: 10
    Last Post: 01-20-2003, 05:27 AM