PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 4, 2022

[FIXED] Why doesn't pointer need type casting when passing it to a function with constant pointer type parameter?

 July 04, 2022     c, pass-by-reference, typecasting-operator     No comments   

Issue

I initialize a char[] array with a "hello" string:

char str[] = "hello";
func(str);

Now, the char[] array is passed to a function, taking a const char* pointer parameter:

void func(const char* str)
{
    puts(str);
}

Output:

hello 

Why don't I need to typecast the char[] array to a const char* pointer?


Solution

Why I don't need to type cast the char type pointer to const char type pointer?

Because of the implicit qualification conversion. In particular, a pointer to a nonconst type can be converted to a pointer to the corresponding const type.

This can be seen from implicit conversion:

A prvalue of type pointer to cv-qualified type T can be converted to a prvalue pointer to a more cv-qualified same type T (in other words, constness and volatility can be added).

"More" cv-qualified means that

  • a pointer to unqualified type can be converted to a pointer to const;

    ...

(emphasis mine)

For example,

int i = 0;
const int *p = &i; // conversion to const happens here


Answered By - Anoop Rana
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing