Usage of const char * const name

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ferdinend
    New Member
    • Jul 2010
    • 7

    Usage of const char * const name

    In the below mentioned code, my intension is only to use the values which are received as a arguments. But unfortunately, I am able to change the “cStringVa l”. How to avoid this?


    Code:
    void setValue(const int * const intVal, const char *  const cStringVal)
    {
    	int length=0;
    
    	//*intVal = 50; //Error Can't change the value
    	
    	
    	//assign the another value
    	strcpy(cStringVal, "India");
    
    }
    Last edited by Niheel; Jul 13 '10, 04:36 AM.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Code:
    int aninta = 5;
    int anintb = 7;
    
    /* Constant pointer to a constant integer
       Pointer can not be altered
       Value pointed at can not be altered
    */
    const int * const cpc = &aninta;
    
    cpc = &anintb;  /* Error */
    *cpc = 10;      /* Error */
    
    /* Pointer to a constant integer
       Pointer can be altered
       Value pointed at can not be altered
    */
    const int * cp = &aninta;
    
    cp = &anintb;  /* OK    */
    *cp = 10;      /* Error */
    
    /* Constant pointer to an integer
       Pointer can not be altered
       Value pointed at can be altered
    */
    int * const pc = &aninta;
    
    pc = &anintb;  /* Error */
    *pc = 10;      /* OK    */
    
    /* Pointer to an integer
       Pointer can be altered
       Value pointed at can be altered
    */
    int * p = &aninta;
    
    p = &anintb;  /* OK    */
    *p = 10;      /* OK    */
    Note that the order of const and int can be interchanged

    Code:
    /* The 2 declarations in each of these two pairs have the same result */
    const int * const cpc1;
    int const * const cpc2;
    
    const int *cp1;
    int const *cp2;

    Comment

    • Ferdinend
      New Member
      • Jul 2010
      • 7

      #3
      Question in on const char * const abc..f

      Hi Banfa,

      Thanks to the reply.
      You are absolutely correct about integer. So that only already I have commented the second line of my program.

      But, like that I should not able to change the character pointer value also. But I am able to change it. (Refer line number 3 of my program). My moto is I should not able to change the "cStringVal " value. How to do this?

      Thanks in Advance,
      Ferdinend.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Are you getting any errors or warnings from the compiler?
        Are you including the header file (string.h) that declares strcpy?
        Take a look in that header and check that the prototype is correct. It should be
        Code:
        char *strcpy( char *destination, const char *source );

        Comment

        Working...