Thread: What does const do in this code?

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    84

    What does const do in this code?

    What is the difference between const and const int in this code? Can't you use just int?

    double priceCanadian(int priceUS)
    {
    const double kgPerLb = .45;

    const double dollarsCanPerUS = 1.26;

    const int pennisePerDollar = 100;

    return priceUS/kgPerLb * dollarsCanPerUS/penniesPerDollar;
    }

  2. #2
    Registered User marCplusplus's Avatar
    Join Date
    Nov 2001
    Posts
    68
    Hi,

    const ..... this shows the variable declared is constant. Cannot be changed throughout the program.

    const int ..... the int shows that the variable is of type integer.

    You could use just int alone, but then, the value of the variable can be changed throughout the program

    The difference between const double and const int is simply the type. Both variables are constant.

    Hope I've helped

    MARC
    No matter how much you know, you NEVER know enough.

  3. #3
    Veni Vidi Vice
    Join Date
    Aug 2001
    Posts
    343
    Agree with marCplusplus. Just wanna add that const has a different use when u using pointers. i.e const int *number means that the actual value cannot be changed but it can point somewhere else. int const *number means that the value can be changed but it cannot point somewhere else.

    Veni Vide Vice

  4. #4
    Blank
    Join Date
    Aug 2001
    Posts
    1,034
    Actually I think the last one
    should be
    int *const number;

    easiest to read it from right to left so you
    say constant pointer to int. And for
    const int* number; and int const* int;
    pointer to a constant int

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  2. Need help implementing a class
    By jk1998 in forum C++ Programming
    Replies: 8
    Last Post: 04-05-2007, 03:13 PM
  3. Another problem with templates
    By robatino in forum C++ Programming
    Replies: 8
    Last Post: 09-21-2006, 04:32 PM
  4. Replies: 7
    Last Post: 06-16-2006, 09:23 PM
  5. Debugging help
    By cuddlez.ini in forum C++ Programming
    Replies: 3
    Last Post: 10-24-2004, 07:08 PM