Thread: Is it Ok to do this?

  1. #1
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218

    Is it Ok to do this?

    I'm going over a code exmple from a book and found something I dident know you could do.

    To start of a constant char* is declared here:
    Code:
    const char* output_filename = NULL;
    But may later be changed here:
    Code:
    output_name = optarg;
    Does this mean that its OK to set a constant char* to NULL and then reassign it w/o a malloc or anything?

  2. #2
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Quote Originally Posted by mike_g View Post
    I'm going over a code exmple from a book and found something I dident know you could do.

    To start of a constant char* is declared here:
    Code:
    const char* output_filename = NULL;
    But may later be changed here:
    Code:
    output_name = optarg;
    Does this mean that its OK to set a constant char* to NULL and then reassign it w/o a malloc or anything?
    Yes.
    const char* means the data it points to can't be changed.
    char* const means the pointer itself can't be changed.

  3. #3
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    const char* means that you can't change the contents of what is being pointed to through the pointer. It doesn't mean the pointer itself is constant.

    char *const (I think that is right) means the pointer itself can not be changed but the data being pointed to can be.

    And of course you can combine them into: const char *const

  4. #4
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    Ok, thanks guys.

Popular pages Recent additions subscribe to a feed