Why return a const value from a function?

This is a discussion on Why return a const value from a function? within the C++ Programming forums, part of the General Programming Boards category; I understand why a function is marked as const but why can you also return a const value from a ...

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    184

    Why return a const value from a function?

    I understand why a function is marked as const but why can you also return a const value from a function? It doesn't make it unchangeable. For example:

    Code:
    const int getInt()
    {
         const int i = 1;
         return i;
    }
    
    //in main function
    int f = getInt();
    
    //This will work
    f += 2;
    So what's the purpose? And how would I mark a variable returned as unchangeable? (Is the only way to mark the local variable I'm putting it into as const?)

  2. #2
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,161
    Quote Originally Posted by 6tr6tr View Post
    I understand why a function is marked as const but why can you also return a const value from a function? It doesn't make it unchangeable. For example:
    There is never a need to return a "const" anything unless it is returned by reference or pointer. The writer of the code snippet might have been trying to emphasize that what the function returns is some "constant" (since it's returning the value of i, which is a const), but it's not necessary and not something I would do.

    EDIT: Accidentally wrote "value" instead of "pointer" in the above paragraph.
    Last edited by brewbuck; 04-10-2008 at 08:57 AM.

  3. #3
    Registered User
    Join Date
    Nov 2006
    Posts
    184
    Quote Originally Posted by brewbuck View Post
    There is never a need to return a "const" anything unless it is returned by reference or value. The writer of the code snippet might have been trying to emphasize that what the function returns is some "constant" (since it's returning the value of i, which is a const), but it's not necessary and not something I would do.
    Thanks. I thought it was a little strange.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  2. Replies: 8
    Last Post: 03-10-2008, 11:57 AM
  3. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 03:13 PM
  4. matrix class
    By shuo in forum C++ Programming
    Replies: 2
    Last Post: 07-13-2007, 01:03 AM
  5. Alegro closes out on me
    By campsoup1988 in forum C++ Programming
    Replies: 8
    Last Post: 04-03-2006, 10:40 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21