Thread: use of static cast

  1. #1
    Registered User
    Join Date
    Dec 2006
    Location
    Jacksonville, AR
    Posts
    91

    Smile use of static cast

    Hey all,
    I have been studying this exercise from "C++ Without Fear". I am new at C++ so it took me a while to follow through the whole program. I have a question though..
    Why is var is_prime needed to be declared as int? The program used a static cast for double. Can't it be declared as double from the beginning?
    It is just a little confusing to me.. Thanks guys and gals, here's the code:


    Code:
    #include <stdafx.h>
    #include <iostream>
    #include <math.h>
    using namespace std;
    
    int main ()
    {
    	int n;  //number to test for prime-ness
    	int i;  //loop counter
    	int is_prime;  //Boolean flag
    
    	//Assume that a number is prime until proven otherwise
    
    	is_prime = true;
    
    	//Get a number from the keyboard
    
    	cout << "Enter a number and press ENTER: ";
    	cin >> n;
    
    	/*Test for prime-ness by checking for divisibility by all whole numbers from 2 to sqrt (n).*/
    
    	i = 2;
    	while (i <= sqrt(static_cast<double>(n))) //While i is <= sqrt(n),
    	{
    		if (n % i ==0)           //If i divides evenly into n,
    			is_prime = false;    //n is not prime.
    		i++;					 //Add 1 to i.
    	}
    	//Print results
    
    	if (is_prime)
    		cout << "Number is prime." << endl;
    	else
    		cout << "Number is not prime." << endl;
    	return 0;
    }

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Well, the first question, is_prime is declared int, but it really should be declare "bool" in my opinion. It may be a case of the author using an older compiler that didn's support "bool" as a type.

    The second question, I take, is why is n declared int, rather than double, and thus forcing the use of static_cast for the sqrt() call... Well, if n is not an integer, you can't really use the modulo operation (and even if you could, it would be quite a bit slower).

    Of course, you don't really want to use sqrt() in a condition. It would be better to do something like
    Code:
      int x = sqrt(static_cast<double>(n));
      while(i < x && is_prime) {
         ... 
      }
    This way, the sqrt() isn't calculated each loop, and the loop ends when we find that a number isn't a prime.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Code:
    while (i <= sqrt(static_cast<double>(n)))
    That is pretty silly, really. For one thing, passing an int to a function that is expecting a double will result in an implicit cast, as long as you have the prototype for the function, which you do. (sqrt()'s prototype is in <math.h> or <cmath>.)

    Code:
    int x = sqrt(static_cast<double>(n));
    That wouldn't do, either. The return value of sqrt() is a double, and that should be casted before being stuffed into an int. I'd use something like
    Code:
    int x = static_cast<int>(sqrt(n));
    Besides, there's a much simpler way to do this! Why not just use this?
    Code:
    while(i*i <= n)
    Sure, i*i might overflow for large numbers, but n is of the same type as i, so it doesn't matter.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    835
    In C++, sqrt() and the other <cmath> functions are overloaded to take and return any of the standard floating-point types (float, double, long double). I'm not sure what it does if passed an integer type.

    http://www.cplusplus.com/reference/c...math/sqrt.html

    > Besides, there's a much simpler way to do this! Why not just use this?

    That's probably safer also, since one has to make sure that if n is an exact square, then i actually takes on the highest value and that rounding error doesn't prevent this. It's probably also faster than sqrt().
    Last edited by robatino; 10-10-2007 at 09:11 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  3. LNK2001 ERROR!!! need help
    By lifeafterdeath in forum C++ Programming
    Replies: 7
    Last Post: 05-27-2008, 05:05 PM
  4. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  5. Replies: 28
    Last Post: 07-16-2006, 11:35 PM