473,804 Members | 2,024 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning a pointer to a constant string

Hi,

I tried to return a pointer to a constant string, but the compiler
gives the following warning if a cast is not used:

warning: assignment from incompatible pointer type

This is the code:
const char msg[] = "Test message";

const char *message(void) {
return msg;
}

int main(void){
const char * str;

str = (const char *)message;
str = (char *)message;
str = message; /* GCC warning! */

str = (const char *)msg;
str = (char *)msg;
str = msg;

return 0;
}

Oddly, GCC only gives the warning if no cast is used, but it doesn't
complain if the cast discards the const qualifier. Is this behavior
OK? I'm using GCC 4.1.2. Thanks!

Best regards,

Santi

Sep 17 '07 #1
23 4785
In article <11************ **********@g4g2 000hsf.googlegr oups.com>,
=?iso-8859-1?q?Santiago_Ur ue=F1a?= <su*****@gmail. comwrote:
>I tried to return a pointer to a constant string, but the compiler
gives the following warning if a cast is not used:
warning: assignment from incompatible pointer type
>This is the code:
>const char msg[] = "Test message";
>const char *message(void) {
return msg;
}
Pay close attention to the placement of the const qualifiers.

const char msg[] says that msg[someindex] will be a const char

const char *message(void)

says that message will return a pointer to a char and that the
pointer is constant. (I think. I'm not -positive-. I haven't had
much occasion to use const.)
--
All is vanity. -- Ecclesiastes
Sep 17 '07 #2
On Mon, 17 Sep 2007 15:38:15 -0700, Santiago Urueña
<su*****@gmail. comwrote:
>Hi,

I tried to return a pointer to a constant string, but the compiler
gives the following warning if a cast is not used:

warning: assignment from incompatible pointer type

This is the code:
const char msg[] = "Test message";

const char *message(void) {
return msg;
}

int main(void){
const char * str;

str = (const char *)message;
str = (char *)message;
str = message; /* GCC warning! */
message is a pointer to a function returning const char *. The
previous two casts are covering up a gratuitous mistake!

Jim
Sep 17 '07 #3
str = (const char *)message;
str = (char *)message;
str = message; /* GCC warning! */

message is a pointer to a function returning const char *. The
previous two casts are covering up a gratuitous mistake!
You are right! Silly me.

Anyway, the compiler doesn't give any warning even if the qualifier is
discarded by the cast:

str = (const char *)message();
str = (char *)message(); /* No warning! */
str = message();

Is this OK?

Thanks again.

Santi

Sep 17 '07 #4
Anyway, the compiler doesn't give any warning even if the qualifier is
discarded by the cast:

str = (const char *)message();
str = (char *)message(); /* No warning! */
str = message();

Is this OK?
After thinking a little more about this, I think I have the answer:
the compiler shouldn't give a warning because a pointer to a non-const
object is being assigned to a pointer to a const object, and this is
totally OK because (anyway you cannot modify the object via the 'str'
pointer).

Thanks

Sep 17 '07 #5
Santiago Urueña <su*****@gmail. comwrites:
str = (const char *)message;
str = (char *)message;
str = message; /* GCC warning! */

message is a pointer to a function returning const char *. The
previous two casts are covering up a gratuitous mistake!
You are right! Silly me.

Anyway, the compiler doesn't give any warning even if the qualifier is
discarded by the cast:

str = (const char *)message();
str = (char *)message(); /* No warning! */
str = message();

Is this OK?
Please leave attribution lines in place for quoted text (i.e., lines
like "So-and-so <fo*@bar.comwri tes:"). They make it easier to
follow the conversation, and it's just polite to credit people for
their words.

A cast specifies a type conversion, but what it *really* does is tell
the compiler "I know exactly what I'm doing, don't bother me with
warnings". Because of that property, almost all casts should be
viewed with suspicion. Adding a cast for the sole purpose of
silencing a compiler warning is almost always a mistake; the correct
solution is usually to fix the code so the cast isn't required, either
by arranging for things to be of the desired type in the first place
or by using types that are converted implicitly.

One of the few cases where a cast is necessary is for some arguments
to variadic functions like printf(). For non-variadic functions, the
compiler knows the required type and is able to generate an implicit
conversion if necessary. For a variadic function, the compiler
doesn't necessarily have this information, so you have to give it some
help.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Sep 17 '07 #6
Santiago Urueña wrote:
>
I tried to return a pointer to a constant string, but the compiler
gives the following warning if a cast is not used:

warning: assignment from incompatible pointer type

This is the code:

const char msg[] = "Test message";

const char *message(void) {
return msg;
}
msg is an array. &msg is a pointer to msg.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>
--
Posted via a free Usenet account from http://www.teranews.com

Sep 17 '07 #7
Santiago Urueña wrote:
Hi,

I tried to return a pointer to a constant string, but the compiler
gives the following warning if a cast is not used:

warning: assignment from incompatible pointer type

This is the code:
const char msg[] = "Test message";

const char *message(void) {
return msg;
}

int main(void){
const char * str;

str = (const char *)message;
str = (char *)message;
str = message; /* GCC warning! */

str = (const char *)msg;
str = (char *)msg;
str = msg;

return 0;
}
const char msg[] = "Test message";
/* msg (above) is a character array, but message is a function */
const char *message(void)
{
return msg;
}

int main(void)
{
const char *str;
str = message(); /* notice parenthesis; message is not a
pointer-to-char but a function
returning a (const) pointer-to-char */
str = msg;
return 0;
}
Sep 18 '07 #8
Hmm as i see it
one type is a char [] and one is char *
that way
str = (char *)message();
works.
// Anders
On 18 Sep, 01:49, CBFalconer <cbfalco...@yah oo.comwrote:
Santiago Urueña wrote:
I tried to return a pointer to a constant string, but the compiler
gives the following warning if a cast is not used:
warning: assignment from incompatible pointer type
This is the code:
const char msg[] = "Test message";
const char *message(void) {
return msg;
}

msg is an array. &msg is a pointer to msg.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account fromhttp://www.teranews.co m

Sep 18 '07 #9
"Walter Roberson" <ro******@ibd.n rc-cnrc.gc.caa écrit dans le message de
news: fc**********@ca nopus.cc.umanit oba.ca...
In article <11************ **********@g4g2 000hsf.googlegr oups.com>,
=?iso-8859-1?q?Santiago_Ur ue=F1a?= <su*****@gmail. comwrote:
>>I tried to return a pointer to a constant string, but the compiler
gives the following warning if a cast is not used:
> warning: assignment from incompatible pointer type
>>This is the code:
>>const char msg[] = "Test message";
>>const char *message(void) {
return msg;
}

Pay close attention to the placement of the const qualifiers.

const char msg[] says that msg[someindex] will be a const char
correct. It could also be written char const msg[].
const char *message(void)

says that message will return a pointer to a char and that the
pointer is constant.
No, such a pointer would be defined as char * const p; and it makes no sense
as a return value for a function.
(I think. I'm not -positive-. I haven't had much occasion to use const.)
It shows!
Please don't post misleading answers on subjects you know you don't master.

--
Chqrlie.
Sep 18 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2069
by: Chris Mantoulidis | last post by:
I see some really weird output from this program (compiled with GCC 3.3.2 under Linux). #include <iostream> using namespace std; int main() { char *s; s = "test1"; cout << "s = " << s << " and &s = " << &s << "\n";
7
2320
by: wonderboy | last post by:
Hey guys, I have a simple question. Suppose we have the following functions:- //-----My code starts here char* f1(char* s) { char* temp="Hi"; return temp;
9
10169
by: kiran.agashe | last post by:
Hi, Please refer program below: #include <string> #include <cstdio> using namespace std; const char* f(); main() {
69
5606
by: fieldfallow | last post by:
Hello all, Before stating my question, I should mention that I'm fairly new to C. Now, I attempted a small demo that prints out the values of C's numeric types, both uninitialised and after assigning them their maximum defined values. However, the output of printf() for the long double 'ld' and the pointer of type void 'v_p', after initialisation don't seem to be right. The compiler used was gcc (mingw) with '-Wall', '-std=c99' and
17
3240
by: djcredo | last post by:
Hey all, I want to return a pointer to a struct. Here is what I'lm trying to do: struct Position{ int x; int y; }; Position* GraphicTag::getRenderCentre(){
36
2292
by: MC felon | last post by:
how do we return strings or arrays from a function? i tried.. char some_func() //where i thought char would tell the compiler that the return is a string { char str; //something; return str; }
19
1844
by: Adam | last post by:
Hi, I'd like to return an (arbitrary length) string array from a function so that after calling the array I've got a list of strings I can access. After much perusing of the internet I found a related answer here (by Eric Sosman) which involved creating an array of pointers and using that, so it looks something like:
8
2221
by: darren | last post by:
Hi everybody, have a quick look at this code: ===== ===== int main(void) { string msg; makeString(msg); cout << "back in main, result = " << msg << endl;
41
2858
by: simonl | last post by:
Hi, I've been given the job of sorting out a crash in our product for which we have the crash information and an avi of the event (which can't possibly match but more of that later...) (btw this is a single threaded VC9 / win32 app) The call stack for the bug effectively goes void* myBuf;
0
10594
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10331
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9166
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7631
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6861
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5529
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5667
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.