gabbar
gabbar

Reputation: 63

Discarded 'const' qualifier at assignment

i have the following code -

int acb(const uint16 *MsgPtr) 
{

uint16 *p = (MsgPtr + 1);
printf("%d", *p);

}

i get the following warning - discarded 'const' qualifier at assignment for the line above printf. How to resolve?

Upvotes: 1

Views: 5713

Answers (3)

ameyCU
ameyCU

Reputation: 16607

You are not allowed to assign a const uint16* value to a uint* pointer . Compiler issues a mere warning in such cases .But you have to gaurantee that you won't try to change what MsgPtr has .

Therefore , change type of p to const uint16 *(With const ,compiler help you to keep your promise of not modifiying the MsgPtr ) or change type of MsgPtr to uint16 * in argument.

Upvotes: 0

autistic
autistic

Reputation: 15642

How to resolve?

  1. Read and understand the error message. In this case, the error message is pointing out a discrepancy between the type of p (int16 *) and the type of MsgPtr (const int16 *). If you don't understand the error message, ask about the error message rather than asking how to resolve the error message.
  2. Since you've read and understood the warning about the missing const qualifier, it ought to make sense that you can either add a const qualifier to one or remove the const qualifier from the other. One of those will generally be the most sensible solution, but they're not the only solutions: You could also explicitly cast the const away, or use the -Wno-discarded-qualifiers compiler flag to suppress the warning; as the courts have heard a million times, it's only undefined behaviour if you attempt to modify an object defined as const.

Upvotes: 2

sweerpotato
sweerpotato

Reputation: 480

The argument to acb is a pointer to a constant uint16, the pointer you're creating is not pointing to a constant. This discards the const qualifier. Either remove const from the argument passed to the function or make p point to a const uint16.

Why is this the case? You tell the compiler you guarantee you won't change what MsgPtr points to, but then create a pointer which can modify what MsgPtr points to by *(p - 1) = ...;

Upvotes: 7

Related Questions