Can somebody please tell what does this function prototype indicate--

const char* fun( char const *,const char*);

Is it some thing like that the return type would always be constant char ? And what is the difference in the two declarations-- char const* and const char*?

Thanks

Recommended Answers

All 4 Replies

Can somebody please tell what does this function prototype indicate--

const char* fun( char const *,const char*);

Is it some thing like that the return type would always be constant char ?

It may be more helpful to read const as "read-only". You the programmer are not supposed to be writing to it. So the function returns a pointer to read-only data (likely a C-style string).

And what is the difference in the two declarations-- char const* and const char*?

Personal preference. char const* - what the pointer is pointing to is read-only. const char* - what the pointer is pointing to is read-only. char *const - the pointer is read-only (may not be incremented, etc.). const char *const - the pointer is read-only (may not be incremented, etc.); what the pointer is pointing to is read-only. char const *const - the pointer is read-only (may not be incremented, etc.); what the pointer is pointing to is read-only.

It may be more helpful to read const as "read-only". You the programmer are not supposed to be writing to it. So the function returns a pointer to read-only data (likely a C-style string).

Thanks for the reply.
I guess I haven't got this thing fully into my lazy brain! So does it actually mean that whatever the arguments maybe , the output can never be manipulated or I'll be always having the same output.

It generally means you shouldn't change what is pointed to.

#include <stdio.h>

const char *foo(const char *text)
{
   puts(text);
   return text;
}

int main(void)
{
   const char literal[] = "non-modifiable string literal";
   char *oops = foo(literal);
   oops[0] = 'N'; /* BAD! */
   return 0;
}

Here the a C++ compiler will prevent you from assigning the return value of foo to oops. But a C compiler may just give you a warning, allowing you to do bad things. Namely, a string literal may be put in program code (or somewhere else that is read-only), and should not be considered to be writable. But the languages do afford you ways to do things you shouldn't.

By const-qualifying the return value, the programmer who gave you the protoype is providing a damn good hint to prevent you from doing things you ought not do. Warnings and errors should then hopefully guide you into writing correct code.

But there is generally no foolproof way of stopping a programmer from doing dumb things and writing code that crashes or otherwise does bad things.

Ok.Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.