LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   g++ warning: deprecated conversion from string constant to 'char*' (https://www.linuxquestions.org/questions/programming-9/g-warning-deprecated-conversion-from-string-constant-to-char%2A-855290/)

chinho 01-10-2011 01:30 AM

g++ warning: deprecated conversion from string constant to 'char*'
 
Hi guys,

My problem is that the warning keeps apperaing when I run g++ compilation.

Say, I have a system runtime function with header (imaginary)sysruntime.h:
void printfunction(char *line);

Then in my .cpp file, I will include the above header
#include <sysruntime.h>

Then, I do the below:
Line12: char *linetoprint = "Print this line";
Line13: printfunction(linetoprint);

But, I will get the warning message "Line12: deprecated conversion from string constant to 'char*'". (Even though it compiles)

My question is how should I declare my char* so that I wont get this warning message, and can still run printfunction(char* line) correctly?

Thks in advance!
Chinho

barriehie 01-10-2011 01:55 AM

Try:
Code:

const char *linetoprint = "Print this line";

dwhitney67 01-10-2011 07:35 AM

Also fix your function to be:
Code:

void printfunction(const char *line);

chinho 01-10-2011 11:36 PM

Hi guys,

In my real situation, the function i described here is actually part of a system runtime library, so I cant change the function as you adviced.

So I think, the adviced below dont work too:
Code:

const char *linetoprint = "Print this line";
Any other suggestions?

Warmest Regards,
Chinho

Aquarius_Girl 01-11-2011 12:04 AM

d.cpp:
Code:

#include <stdio.h>
#include "d.h"

int main ()
{
    char *linetoprint = (char*)"Print this line";
   
    printfunction (linetoprint);
   
    return 0;
}

void printfunction (char*d)
{
  printf ("%s", d);
}

Code:

anisha@linux-uitj:~> g++ d.cpp -Ld.h -Wall -Wextra
anisha@linux-uitj:~>


dwhitney67 01-11-2011 03:49 AM

Code:

const char* linetoprint = "Print this line";

printfunction(const_cast<char*>(linetoprint));

What system library offers printfunction()??

chinho 01-12-2011 03:06 AM

Hi anisha, thanks a gazillion!

Hi whitney, none. I was only stating an example :)

Aquarius_Girl 01-12-2011 03:09 AM

Quote:

Originally Posted by chinho (Post 4221410)
Hi anisha, thanks a gazillion!

Most welcome, mark the thread solved if you think...it is solved.


All times are GMT -5. The time now is 03:37 PM.