-2

I am not an expert in C++. I get an error when I try to execute the following line in C++. However, I don't get this error in C. Can you please explain why does it happen so?

 int  policy;
 char *policy_name = (policy == SCHED_FIFO) ? "SCHED_FIFO" : (policy == SCHED_RR) ? "SCHED_RR" : (policy == SCHED_OTHER) ? "SCHED_OTHER":"??";

Compilation error:

error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]

If I do this, the error goes off.

 const char *policy_name = (policy == SCHED_FIFO) ? "SCHED_FIFO" : (policy == SCHED_RR) ? "SCHED_RR" : (policy == SCHED_OTHER) ? "SCHED_OTHER":"??";

The question is why does it happen so?

dexterous
  • 6,422
  • 12
  • 51
  • 99
  • 2
    The error says it all. No error in C doesn't mean that you are safe with this in C. Indeed, you generate a segmentation fault if you really treat this immutable string as mutable lateron, even in C. It's just that your C++ compiler won't let you do it in the first place. For a good reason. – poljpocket Jan 07 '14 at 07:05
  • Either way, you should declare the variable as a `const char*` rather than a `char*` because those are constant string literals. Even though it may compile successfully, it would still invoke undefined behavior. – C0deH4cker Jan 07 '14 at 07:05
  • In C++, the type of a string literal is `const char[]`, but in C the type of a string literal is `char []`. [More details in this answer](http://stackoverflow.com/questions/2245664/string-literals-in-c). – Raymond Chen Jan 07 '14 at 07:12

1 Answers1

5

The question is why does it happen so?

Because the type of "SCHED_FIFO" (and other string-literals) is char const[N]1 which converts into char const*. That means, the type of right expression is const char* which cannot be assigned to char*.

char *policy_name = (policy == SCHED_FIFO) ? "SCHED_FIFO" :  .......
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                    type of this expression is char const*

But once you make the left side const char* also2 then it compiles fine!

Hope that helps.


1. where N is some integral constant value.
2. BTW, const char* and char const* are the same thing! I've this habit of writing char const* instead of const char*, but they're interchangeable.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
Nawaz
  • 353,942
  • 115
  • 666
  • 851