Understanding 'Assignment Discards Const Qualifier from Pointer Target Type': Solutions and Best Practices

David Henegar

This documentation aims to provide a comprehensive guide on understanding and solving the warning message "assignment discards 'const' qualifier from pointer target type" in the C programming language. We will cover the cause of this warning and provide step-by-step solutions and best practices to avoid this issue in the future.

Table of Contents

  • What is 'const' qualifier?
  • Why does the warning occur?
  • Solutions and Best Practices
  • Using const-correctness
  • Casting away const-ness

What is 'const' qualifier? {#what-is-const-qualifier}

In C, the const keyword is used to declare a variable that cannot be modified after initialization. It is a form of compile-time enforcement to guarantee that the value of a variable remains unchanged throughout the program. The const keyword is also used to indicate that a function does not modify the object pointed to by a pointer argument.

Consider the following example:

Why does the warning occur? {#why-does-the-warning-occur}

The "assignment discards 'const' qualifier from pointer target type" warning occurs when you try to assign a pointer to a non-const object to a pointer to a const object. This is because doing so would allow the modification of the const object through the non-const pointer, which is not allowed.

For example:

In the above example, the compiler will generate a warning because assigning the address of a const object (x) to a non-const pointer (p) could lead to the modification of the const object, which is not allowed.

Solutions and Best Practices {#solutions-and-best-practices}

Using const-correctness {#using-const-correctness}.

The best practice to avoid this warning is to ensure const-correctness in your code. When working with const objects, always use const pointers. This will prevent you from accidentally modifying const objects and will help you catch potential issues during compilation.

For example, the following code is const-correct and will not generate any warning:

Casting away const-ness {#casting-away-const-ness}

In some cases, you might need to cast away the const-ness of an object. This should be done with caution and only when you are sure that the object will not be modified. You can use a typecast to remove the const qualifier from a pointer:

Keep in mind that casting away const-ness can lead to undefined behavior if you attempt to modify the object through the non-const pointer. Therefore, it is recommended to only use this approach when absolutely necessary and when you are sure that the object will not be modified.

What is const-correctness? {#what-is-const-correctness}

Const-correctness is a programming practice that ensures the proper use of const qualifiers in your code. It involves using const pointers when working with const objects and preventing the modification of const objects through non-const pointers.

Why should I use const pointers? {#why-should-i-use-const-pointers}

Using const pointers helps to maintain the integrity of const objects and prevents accidental modifications. It also helps to catch potential issues during compilation by generating warnings when you try to assign a const object to a non-const pointer.

Can I modify a const object using a non-const pointer? {#can-i-modify-a-const-object-using-a-non-const-pointer}

Modifying a const object through a non-const pointer leads to undefined behavior. While it is possible to cast away the const-ness of an object, doing so should be done with caution and only when you are sure that the object will not be modified.

When should I cast away const-ness? {#when-should-i-cast-away-const-ness}

Casting away const-ness should be done cautiously and only when absolutely necessary. It is recommended to use this approach when you are sure that the object will not be modified and when there is no other way to accomplish your task without casting away const-ness.

How can I ensure const-correctness in my code? {#how-can-i-ensure-const-correctness-in-my-code}

To ensure const-correctness in your code, always use const pointers when working with const objects, and never attempt to modify const objects through non-const pointers. Make sure to follow the proper use of const qualifiers in your code and pay attention to compiler warnings related to const-ness.

Additional Resources

  • C Programming: const Keyword
  • Understanding const in C: A Complete Guide
  • A Guide to Undefined Behavior in C and C++

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Lxadm.com.

Your link has expired.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.

AOverflow.com

AOverflow.com Logo

warning: assignment discards 'const' qualifier from pointer target type

I am implementing the strchr function with the following prototype:

and whose code is:

with a small main to prove it.

When executing the program it gives me the following warning:

I understand that it is because of working with a constant variable and making an assignment, but I can't understand what is the root of the problem and how to solve it.

Isn't doing the assignment like making a "copy" of the pointer *s and storing it in *aux, later working with the "copy"?

assignment discards 'const' qualifier from pointer target type

First of all, you have to understand what this statement means:

The code above is interpreted like this: " s it's a pointer to a constant character", in other words, you're telling the compiler: "Hey man, s it points to a character that is a constant, its value shouldn't change".

Since pa it points to a constant integer, it is illegal to dereference the pointer , for that reason this expression leads to an error: *pa = 1 , because pa it cannot modify the variable a (it doesn't matter if a it wasn't declared as a constant variable, the expression is still illegal).

Once you know this, it's easy to see why the compiler throws a warning on this line:

I go back and repeat: s it is a pointer that points to a constant character, instead it aux points to a character (it can be modified, because there is no such restriction), for that reason the compiler complains, because aux now it will be able to modify the character to which the pointer points s .

Now you may be wondering, is this really a problem? If we execute your code it will surely work but the code will be confusing, because first you indicate that the value it points to s should not be modified and then aux if it can be modified, then it is not clear what the intention of the code is.

In fact, the purpose of this statement:

It is being able to indicate to other developers that they s should NEVER modify the value to which it refers. This helps to avoid possible errors, since in this way the developer will not intentionally modify (as you know, programmers are clueless) the value that the pointer points to.

Answering questions...

Of course yes.

This line is simple to interpret:

You're copying the memory address pointed s to by aux , at the end aux and s they point to the same thing. The problem with that assignment is that you aux can modify the value you point to s . This warning is simple to solve, put the const in the declaration:

In fact, the pointer aux is unnecessary, you can remove it and work directly with s .

A LOT OF EYE: Do not be confused with this statement:

In that case s it is a constant pointer that points to a character, this means that you cannot modify the content of the pointer.

Web Analytics Made Easy - Statcounter

assignment discards 'const' qualifier from pointer target type

Const Qualifier In C

Const Qualifier In C

Table of Contents

In C programming, there’s something called the “const” qualifier. It’s like a rule that says once you set a value to something, you can’t change it. This is really important because it helps make sure data in a program stays reliable and doesn’t get messed up accidentally. In this discussion about “const” in C, we’ll look at how to use it and why it’s useful for C programmers. Knowing about “const” is a big part of writing code in C that’s strong and easy to understand.

What is a Const Qualifier

You can use the “const” qualifier in C to declare a variable and make sure it doesn’t change its value. However, it’s important to note that, depending on where the const variable is stored, you might still be able to change its value using a pointer, but this isn’t recommended.

Using “const” in C is a good idea when you want to make sure certain values stay the same and don’t get accidentally changed. It’s a way to keep your code reliable and prevent unexpected modifications.

1. Constant Variables

const is used to declare a variable  var  as a constant with an initial value of 100 in the given example. The value of this variable cannot be modified once it is initialized. Refer to the following example given :

2. Pointer to Constant

You can modify a pointer to point to a different integer variable, but you can’t change the value of the actual object (the thing it’s pointing to) using that pointer. The pointer itself is stored in an area where you can read and write data, like the stack. Refer to the example below:

Example 2: Program where variable i itself is constant

In C++ and C, down qualification is not allowed and can lead to issues or warnings. Down qualification occurs when you assign a qualified type (e.g., const-qualified) to a non-qualified type. This means that if you have a pointer or reference to a const-qualified object and you try to assign it to a non-const pointer or reference, it will likely result in a compilation error in C++

Example 3: Program to show down qualifications

3. Constant Pointer to Variable

The declaration you provided is for a pointer to a constant integer, not a constant pointer to an integer. In C and C++, these two declarations have different meanings

Advantages of const Qualifier In C

Using the const keyword in your code offers several advantages:

  • Improved Code Readability: When you mark a variable as const , you’re telling other programmers that its value shouldn’t change. This makes your code easier for others to understand and maintain.
  • Enhanced Type Safety: By using, you can prevent accidental modifications to values, reducing the chances of bugs and errors in your code. It adds an extra layer of protection.
  • Improved Optimization: Compilers can optimize const variables more effectively because they know these values won’t change during program execution. This optimization can result in faster and more efficient code.
  • Better Memory Usage: Declaring variables as const can often eliminate the need to create unnecessary copies of values, reducing memory usage and improving overall performance.
  • Improved Compatibility: Using const in your code can enhance compatibility with other libraries and APIs that also use const variables. It helps ensure that your code plays well with others.
  • Improved Reliability: const helps make your code more reliable by preventing unexpected value modifications, and reducing the risk of bugs and errors in your program.

In summary, incorporating the const keyword in your code can lead to more readable, reliable, and optimized software while enhancing compatibility with other code and libraries.

FAQ – Const Qualifier In C

Q1. what is the const qualifier.

Ans. The const qualifier serves as a clear declaration that a data object’s value cannot be changed once it’s initialized. In other words, it’s a way of saying, “This thing won’t change after I set its value.” This means you can’t use const data objects in situations where a change is expected or required. For example, you can’t use a const data object on the left side of an assignment statement because it’s not allowed to be modified once it has a value.

Q2. Why do we require const qualifier in C with example?

Ans. The const qualifier designates a variable as unchangeable after initialization. This is valuable for constants like PI, enhancing code readability and preventing errors.

Q3. What is const and volatile qualifier in C?

Ans. The const keyword ensures a pointer can’t change after initialization, protecting it from modification. In contrast, the volatile keyword indicates that a value can be changed by external actions beyond the user’s control.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

What Is The Future Of SEO In 2024

Character Arithmetic In C and C++

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

Reach Out to Us for Any Query

SkillVertex is an edtech organization that aims to provide upskilling and training to students as well as working professionals by delivering a diverse range of programs in accordance with their needs and future aspirations.

© 2024 Skill Vertex

  • STMicroelectronics Community
  • STM32 MCUs products

assignment discards volatile qualifier problem

  • Subscribe to RSS Feed
  • Mark Topic as New
  • Mark Topic as Read
  • Float this Topic for Current User
  • Printer Friendly Page

WM_IR

  • Mark as New
  • Email to a Friend
  • Report Inappropriate Content

‎2021-06-10 07:01 AM

0693W00000BadmeQAB.png

Solved! Go to Solution.

  • All forum topics
  • Previous Topic

TDK

‎2021-06-10 07:41 AM

View solution in original post

waclawek.jan

‎2021-06-10 07:27 AM

‎2021-06-11 12:29 AM

Ozone

‎2021-06-11 01:14 AM

‎2021-06-11 01:23 AM

‎2021-06-11 07:15 AM

assignment discards 'const' qualifier from pointer target type

  • Touch Sensing Library (STM32Cube_FW_L0_V1.12.1) uses delay which depends on fixed system clock! in STM32 MCUs Embedded software 2023-12-01
  • CAN Protocol Receiver isn't working in STM32 MCUs products 2023-01-28
  • DMA1 CCR register is NOT updated (NOT Written) in STM32 MCUs products 2021-12-26
  • Volatile qualifier does not matter in my interrupt routine in STM32 MCUs products 2021-06-13

Compiler warnings: assignment discards 'const' qualifier from pointer target type

Description.

Compiling LVGL (v8.0.2) code (RISC-V GCC, 8.3.0) I see these warnings:

lvgl/src/widgets/lv_checkbox.c:123:13: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]

lvgl/src/core/lv_obj.c:132:18: warning: initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]

lvgl/src/extra/widgets/tabview/lv_tabview.c:84:25: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]

lvgl/src/extra/widgets/tabview/lv_tabview.c:93:24: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]

lvgl/src/extra/widgets/tabview/lv_tabview.c:95:37: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]

lvgl/src/extra/widgets/tabview/lv_tabview.c:97:37: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]

lvgl/src/extra/widgets/tabview/lv_tabview.c:196:21: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]

What MCU/Processor/Board and compiler are you using?

RISC-V (GCC 8.3.0), custom platform

What do you want to achieve?

Clean LVGL build with no discarded-qualifiers warnings. I’d like to treat them as errors (-Werror), but currently LVGL prevents me from doing this. It should be easy to fix these.

What have you tried so far?

Adding -Wno-discarded-qualifiers option: the build works, but I’d like to avoid having to add this option.

Code to reproduce

Screenshot and/or video.

(cc @kisvegabor )

Currently, our CI uses -Wno-discarded-qualifiers ; this would need to be changed if we are going to consider this a disallowed warning.

Unfortunately, I can’t see these warnings with GCC 7.5.0, but I agree that it’d be better to enable them.

If @embeddedt also agrees the enable discarded-qualifiers warnings, @marcinh0001 , can you send a PR with the fixes?

I could, but as I explained in another thread, I’m required to add copyright notices to all files I modify, even slightly. I’d like to avoid it, it’s too many files. Would it be possible for someone else to get rid of discarded-qualifiers warnings?

I can do it, however, I need to find a way of getting them to show up first, as when I enabled -Wdiscarded-qualifiers locally last week, they weren’t appearing.

Thanks. I think you’ll need a sufficiently fussy compiler (probably meaning modern?) I don’t have a full view of which GCC versions are / aren’t fussy about it, but these two I use definitely are:

  • 8.3.0 for RISC-V
  • 10.2.0 for x86 used under mingw

And, needless to say, you need to get rid of the -Wno-discarded-qualifiers option.

:slight_smile:

I am having the same issues. Environment is

Win 11 pro PlatformIO using Arduino framework lvgl 8.3.4 ESP32DEV module when compiling lvgl, i get several messages like

when using squarline studio 1.2.x, even more of such messages show up. Unfortunately, when I try to disable warning by specifying -Wno-discarded-qualifiers I get informed that this is not allowed in a C++ compile environment. Now, there shouldn’t be any warnings when compiling anyhow, so - what do I have to do to have this situation remedied?

With best regards

Volker Bandke

Same here, I’m working with the latest version of LVGL and PlatformIO using the Arduino Framework. I would like to suppress this warning using the build flag -Wno-discarded-qualifiers However, as previously mentioned, this is not allowed in C++.

Is there another way to suppress this warning globally?

corrects the warning:

src\core\lv_obj.c 143

const uint8_t * txt_u8; txt_u8 = (const uint8_t *)txt;

src\extra\widgets\tabview 81 const char ** new_map;

src\extra\widgets\tabview 107 tabview->map = (char **)new_map;

src\extra\widgets\tabview 228 tabview->map[0] = (char *)"";

\src\widgets\lv_checkbox.c 125 cb->txt = (char *)"Check box";

Great! Are you going to issue a pull request?

const在指针赋值时候注意事项:assignment discards ‘const’ qualifier from pointer target type的解决方法

assignment discards 'const' qualifier from pointer target type

const 与 define 都可以创建类似功能的符号常量。但是const可以创建const-数组、指针、指向const的指针。很重要的一点const能使不需要修改的数据变成只读的模式:

以上的代码会出现错误: assignment discards ‘const’ qualifier from pointer target type , 

字面意思是:赋值从指针目标类型中丢弃“const”限定符 , 也就是说const这个限定符号被丢弃了。其实从程序中可以看出来,因为指针 pnc 是普通指针,那么就可以改修这个指针所指向的值或者重新赋值。

但是这个指针指向的值是一个const的数组,  那么也就是说const double locked[ ] 这个数组里面的值变的能被修改了,  这显然跟const 不能修改(只读)所冲突。 

解决方法是: 把 指针也变成const 类型,这样 const 类型的数组locked 的地址就能赋给 const类型的指针pnc。

总结: 能把   const 数据(locked[ ])的地址 

 或    非 const数据(rate[ ])的地址 

初始化为 指向const的指针( const double *pnc ) 或为其赋值 (pnc = locked; pnc = &rate[ 3]) 是正确的。  

反之  非 const数据的地址只能赋给普通的指针 ,如果将const的数据地址赋给普通的(非const)的指针,  那么 这个cost的数据将不在变成"只读"的状态,而是能 被修改 。

assignment discards 'const' qualifier from pointer target type

请填写红包祝福语或标题

assignment discards 'const' qualifier from pointer target type

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

assignment discards 'const' qualifier from pointer target type

assignment discards 'const' qualifier from pointer target type

  • Latest Articles
  • Top Articles
  • Posting/Update Guidelines
  • Article Help Forum

assignment discards 'const' qualifier from pointer target type

  • View Unanswered Questions
  • View All Questions
  • View C# questions
  • View C++ questions
  • View Javascript questions
  • View Visual Basic questions
  • View .NET questions
  • CodeProject.AI Server
  • All Message Boards...
  • Running a Business
  • Sales / Marketing
  • Collaboration / Beta Testing
  • Work Issues
  • Design and Architecture
  • Artificial Intelligence
  • Internet of Things
  • ATL / WTL / STL
  • Managed C++/CLI
  • Objective-C and Swift
  • System Admin
  • Hosting and Servers
  • Linux Programming
  • .NET (Core and Framework)
  • Visual Basic
  • Web Development
  • Site Bugs / Suggestions
  • Spam and Abuse Watch
  • Competitions
  • The Insider Newsletter
  • The Daily Build Newsletter
  • Newsletter archive
  • CodeProject Stuff
  • Most Valuable Professionals
  • The Lounge  
  • The CodeProject Blog
  • Where I Am: Member Photos
  • The Insider News
  • The Weird & The Wonderful
  • What is 'CodeProject'?
  • General FAQ
  • Ask a Question
  • Bugs and Suggestions

C Warning - assignment discards qualifiers from pointer target type

assignment discards 'const' qualifier from pointer target type

Add your solution here

Your Email  
Password  
Your Email  
?
Optional Password  
  • Read the question carefully.
  • Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  • If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Print

Top Experts
Last 24hrsThis month
145
40
40
25
25
950
669
235
205
145

assignment discards 'const' qualifier from pointer target type

  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

Const Qualifier in C

The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed (which depends upon where const variables are stored, we may change the value of the const variable by using a pointer). The result is implementation-defined if an attempt is made to change a const.

Using the const qualifier in C is a good practice when we want to ensure that some values should remain constant and should not be accidentally modified.

In C programming, the const qualifier can be used in different contexts to provide various behaviors. Here are some different use cases of the const qualifier in C:

1. Constant Variables

In this case, const is used to declare a variable var as a constant with an initial value of 100. The value of this variable cannot be modified once it is initialized. See the following example:

2. Pointer to Constant

We can change the pointer to point to any other integer variable, but cannot change the value of the object (entity) pointed using pointer ptr. The pointer is stored in the read-write area (stack in the present case). The object pointed may be in the read-only or read-write area. Let us see the following examples.

Example 2: Program where variable i itself is constant.

Down qualification is not allowed in C++ and may cause warnings in C. Down qualification refers to the situation where a qualified type is assigned to a non-qualified type.

Example 3: Program to show down qualification.

3. Constant Pointer to Variable

The above declaration is a constant pointer to an integer variable, which means we can change the value of the object pointed by the pointer, but cannot change the pointer to point to another variable.

4. Constant Pointer to Constant

The above declaration is a constant pointer to a constant variable which means we cannot change the value pointed by the pointer as well as we cannot point the pointer to other variables. Let us see with an example. 

Advantages of const Qualifiers in C

The const qualifier in C has the following advantages:

  • Improved Code Readability: By marking a variable as const, you indicate to other programmers that its value should not be changed, making your code easier to understand and maintain.
  • Enhanced Type Safety : By using const, you can ensure that values are not accidentally modified, reducing the chance of bugs and errors in your code.
  • Improved Optimization: Compilers can optimize const variables more effectively, as they know that their values will not change during program execution. This can result in faster and more efficient code.
  • Better Memory Usage: By declaring variables as const, you can often avoid having to make a copy of their values, which can reduce memory usage and improve performance.
  • Improved Compatibility : By declaring variables as const, you can make your code more compatible with other libraries and APIs that use const variables.
  • Improved Reliability : By using const, you can make your code more reliable, as you can ensure that values are not modified unexpectedly, reducing the risk of bugs and errors in your code.
Type Declaration Pointer Value Change
(*ptr = 100)
Pointing Value Change
(ptr  = &a)
int * ptr Yes Yes
const int * ptr
int const * ptr
No Yes
int * const ptr Yes No
const int * const ptr No No

This article is compiled by “ Narendra Kangralkar “.

Please Login to comment...

Similar reads.

  • C-Storage Classes and Type Qualifiers
  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • What is OpenAI SearchGPT? How it works and How to Get it?
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Home Posts Topics Members FAQ

95910

Write:

const char *str;
str = Inet_ntop(...); //returns const char *
The function returns type 'const char*' for a reason.
It's telling you "You can look, but don't touch the
target of the returned pointer."

HTH,
-Mike


Write:

const char *str;
str = Inet_ntop(...); //returns const char *
The function returns type 'const char*' for a reason.
It's telling you "You can look, but don't touch the
target of the returned pointer." If you ignore this
warning, you're on your own.

HTH,
-Mike



You should declare str variable to be the same type as that being
returned by Inet_ntop().

const char *str = Inet_ntop(/* ... */);

The "const" is a qualifier. It means the return value of Inet_ntop
is a pointer to data that should not be modified.

However, in the erroneous code, you assigned that pointer to a
regular "char *", which discards the "should not be modified"
qualifier.

-- James


It can get confusing. :-)

/* (0) */ int * pi; /* pointer to int */
/* (can modify p or *p) */

/* (1) */ int const * pci; /* pointer to const int */
/* (can modify p, but not *p) */

/* (2) */ const int * pci2; /* same as (1) */

/* (3) */ int * const cpi; /* const pointer to int */
/* (can modify *p, but not p */

/* (4) */ int const * const cpci; /* const pointer to const int */
/* (cannot modify p nor *p) */

/* (5) */ const int * const cpci2; /* same as (4) */
HTH,
-Mike


Dang, that's what I get for 'copy-n-pasting' :-)

Of course the 'p' and '*p' in the comments refer to
the actual identifier in each declaration
('pci', 'cpi', etc.)

Sorry about that.

-Mike

| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:
| last post by:

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.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

warning: assignment discards ‘const’ qualifier from pointer target type #107

@osalbahr

osalbahr commented Nov 22, 2023

Hello, I noticed the following when upgrading my system:

Just wanted to double-check if this warning is expected.

@davidjo

davidjo commented Nov 22, 2023

yes this is an expected error - I seem to remember at the time I couldnt figure a way to remove this warning.

Sorry, something went wrong.

@osalbahr

davidjo commented Jan 24, 2024

Added fix for this.

@davidjo

Successfully merging a pull request may close this issue.

@davidjo

assignment discards 'const' qualifier from pointer target type

Little-Prince

解决 assignment discards 'const' qualifier from pointer target type 的问题.

用上述语句调用外部库函数 "external_library_function" 编译时总是报 

这种情况说明该函数返回的是一个指向常量或变量的指针,修改十分容易,只需要将 "fr"  的定义改为 const float,

问题解决了,但还是要进一步思考指针和 const 一起用时的几个注意点:

1. const float *p  p 是指向常量或变量的指针, 指向可以改变。

2. float *const p  p不可以指向常量或常变量,指向确定后不可更改。

3. const float *const p p可以指向常量或变量,指向确定后不可更改。

posted on 2020-06-27 11:41   Little-Prince   阅读( 5513 )  评论( 0 )  编辑   收藏   举报

assignment discards 'const' qualifier from pointer target type

Powered by: 博客园 Copyright © 2024 Little-Prince Powered by .NET 8.0 on Kubernetes

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

assignment discards ‘const’ qualifier from pointer target type - When trying to retrieve a value

Couchbase uses an event-based model. So in order to retrieve values I have to set up a call-back handler and then throw a get-request at the database. It is done like this:

In the get_callback I have a cookie to put my values into. So I parse the object I get back and put it into the cookie via:

When I want to retrieve it I have to use lcb_get_cookie man page which returns a void pointer but says: "lcb_get_cookie() returns the value set by lcb_set_cookie(), or NULL if no value is set by lcb_set_cookie()." So I want to do something like:

When I try to use it like this I get a warning: warning: assignment discards ‘const’ qualifier from pointer target type [enabled by default] . So I'm confused. How can I retrieve the value I put into the cookie?

Edit: I forgot to mention that I need to further process the data and want to make changes to it.

Sören Titze's user avatar

Tell compiler that you promise not to change that cookie:

But if you need to change it, you could perhaps cast it, because manual says that "...libcouchbase will not do anything with the value." :

But maybe safer alternative would be to copy the contents to a new cookie, make changes and set it again?

I don't know the exact layout of json_t , by if it does not contain any internal pointers, simple assignment might do the trick:

user694733's user avatar

  • That's the thing. I want to make changes to it. I forgot to mention it and will edit my question. –  Sören Titze Commented Oct 3, 2013 at 11:53
  • I like the idea of copying it. How would I go about doing it? My grasp of C is still very rudimental. - Thank you for your quick and thorough help good sir! –  Sören Titze Commented Oct 3, 2013 at 12:03

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c couchbase or ask your own question .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • How do you determine what order to process chained events/interactions?
  • Should I report a review I suspect to be AI-generated?
  • Dress code for examiner in UK PhD viva
  • My visit is for two weeks but my host bought insurance for two months is it okay
  • Exact time point of assignment
  • What to call a test that consists of running a program with only logging?
  • The answer is not wrong
  • Variable usage in arithmetic expansions
  • Could someone tell me what this part of an A320 is called in English?
  • Is having negative voltages on a MOSFET gate a good idea?
  • Topology on a module over a topological ring
  • What explanations can be offered for the extreme see-sawing in Montana's senate race polling?
  • What was I thinking when I made this grid?
  • Why does Russia strike electric power in Ukraine?
  • `Drop` for list of elements of different dimensions
  • What prevents a browser from saving and tracking passwords entered to a site?
  • Passport Carry in Taiwan
  • Why doesn't the world fill with time travelers?
  • 3 Aspects of Voltage that contradict each other
  • How Can this Limit be really Evaluated?
  • Fill a grid with numbers so that each row/column calculation yields the same number
  • DATEDIFF Rounding
  • What did the Ancient Greeks think the stars were?
  • My colleagues and I are travelling to UK as delegates in an event and the company is paying for all our travel expenses. what documents are required

assignment discards 'const' qualifier from pointer target type

Public signup for this instance is disabled . Go to our Self serve sign up page to request an account.

Uploaded image for project: 'Guacamole'

  • GUACAMOLE-1736

video.c:63:22: error: assignment discards ‘const’ qualifier from pointer target type [-Werror=discarded-qualifiers]

assignment discards 'const' qualifier from pointer target type

  • Status: Closed
  • Resolution: Duplicate
  • Affects Version/s: 1.5.0
  • Fix Version/s: None
  • Component/s: guacamole
  • Labels: None
  • Environment: Ubuntu 22.10

Description

Hello under latest ubuntu when i update guacamole from 1.4 to 1.5 when i write "sudo make" in guacamole-server i have this error:

ps: i have installed libavformat-dev and ffmpeg package

make [2] : Entering directory '/home/kpietrasiak/guacamole-server-1.5.0/src/guacd'  /usr/bin/mkdir -p '/usr/bin'   /bin/bash ../../libtool   --mode=install /usr/bin/install -c guacd '/usr/bin' libtool: install: /usr/bin/install -c .libs/guacd /usr/bin/guacd  /usr/bin/mkdir -p '/usr/share/man/man5'  /usr/bin/install -c -m 644 man/guacd.conf.5 '/usr/share/man/man5'  /usr/bin/mkdir -p '/usr/share/man/man8'  /usr/bin/install -c -m 644 man/guacd.8 '/usr/share/man/man8'  /usr/bin/mkdir -p '/usr/lib/systemd/system'  /usr/bin/install -c -m 644 systemd/guacd.service '/usr/lib/systemd/system' make [2] : Leaving directory '/home/kpietrasiak/guacamole-server-1.5.0/src/guacd' make [1] : Leaving directory '/home/kpietrasiak/guacamole-server-1.5.0/src/guacd' Making install in src/guacenc make [1] : Entering directory '/home/kpietrasiak/guacamole-server-1.5.0/src/guacenc'   CC       guacenc-video.o video.c: In function ‘guacenc_video_alloc’: video.c:63:22: error: assignment discards ‘const’ qualifier from pointer target type [-Werror=discarded-qualifiers]    63 |     container_format = container_format_context->oformat;       |                      ^ video.c:66:22: error: initialization discards ‘const’ qualifier from pointer target type [-Werror=discarded-qualifiers]    66 |     AVCodec* codec = avcodec_find_encoder_by_name(codec_name);       |                      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ cc1: all warnings being treated as errors make [1] : *** [Makefile:1126: guacenc-video.o] Error 1 make [1] : Leaving directory '/home/kpietrasiak/guacamole-server-1.5.0/src/guacenc' make: *** [Makefile:544: install-recursive] Error 1

Attachments

Issue links.

Task - A task that needs to be done.

IMAGES

  1. How to modify a const variable in C?

    assignment discards 'const' qualifier from pointer target type

  2. PPT

    assignment discards 'const' qualifier from pointer target type

  3. Day 22

    assignment discards 'const' qualifier from pointer target type

  4. warning: passing argument 3 of 'disp_32x32' discards 'const' qualifier

    assignment discards 'const' qualifier from pointer target type

  5. warning:discards qualifiers from pointer target type解决办法-CSDN博客

    assignment discards 'const' qualifier from pointer target type

  6. c: discards ‘const’ qualifier from pointer target type

    assignment discards 'const' qualifier from pointer target type

COMMENTS

  1. warning: assignment discards qualifiers from pointer target type

    The &str[strIndex-1] expression has type const char*. You are not allowed to assign a const char* value to a char * pointer. That would violate the rules of const-correctness.

  2. warning: "assignment discards 'const' qualifier from pointer target type"

    You could change the signature of myStrTod so that your output is to a pointer to const char: float myStrTod(const char *nPtr, const char **endPtr); Then GCC will report a different error: 40937624.c: In function 'main': 40937624.c:11:25: warning: passing argument 2 of 'myStrTod' from incompatible pointer type [-Wincompatible-pointer ...

  3. [Resolved] assignment discards qualifiers from pointer target type

    Joined: 23 Jun 2008. Posts: 469 View Posts. I have some code that is giving me a warning... assignment discards qualifiers from pointer target type Here it is... const XCHARItemList [] ="Line1\n ""Line2\n ""Line3\n "; XCHAR* pTemp; pTemp =ItemList ; // <--- warning on this line. Since the code is not working right, I assume that the warning may ...

  4. Assignment Discards Const Qualifier From Pointer Target Type (Resolved)

    The "assignment discards 'const' qualifier from pointer target type" warning occurs when you try to assign a pointer to a non-const object to a pointer to a const object. This is because doing so would allow the modification of the const object through the non-const pointer, which is not allowed. For example: In the above example, the compiler ...

  5. warning: assignment discards 'const' qualifier from pointer target type

    Learn why the compiler warns about assigning a constant pointer to a non-constant pointer and how to fix it. See the code example, the explanation and the solution for the strchr function.

  6. resolve warning: assignment discards 'const' qualifier from pointer

    I think the most pragmatic solution would be to change the type of sc_apdu_t.data back to const and cast the few occurences where non-const is needed. Windows warnings need to be fixed from peoples using OpenSC Windows.

  7. Const Qualifier In C

    main.c: In function 'main': main.c:16:9: warning: assignment discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers] 16 | ptr = &j; | ^ *ptr: 10 *ptr: 20 3. Constant Pointer to Variable int* const ptr; The declaration you provided is for a pointer to a constant integer, not a constant pointer to an integer. ...

  8. Wdiscarded-qualifiers: assignment discards 'const' qualifier from

    Wdiscarded-qualifiers: assignment discards 'const' qualifier from pointer target type #6151. Open sgoveas opened this issue May 10, 2022 · 2 comments Open Wdiscarded-qualifiers: assignment discards 'const' qualifier from pointer target type #6151. sgoveas opened this issue May 10, 2022 · 2 comments Labels. Future work Improvement-Tech-Debt.

  9. Solved: assignment discards volatile qualifier problem

    Options. 2021-06-11 07:15 AM. Volatile means the compiler is prevented from optimizing out accesses to that variable. When the compiler generates code for a function, it does so with this in mine. Removing the qualifier would break this restriction as functions generated without this qualifier would not adhere to the restriction.

  10. Compiler warnings: assignment discards 'const' qualifier from pointer

    warning: assignment discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers] new_map[1] = ""; when using squarline studio 1.2.x, even more of such messages show up. Unfortunately, when I try to disable warning by specifying

  11. Nginx Compile Error: "assignment discards 'const' qualifier from

    Nginx Compile Error: "assignment discards 'const' qualifier from pointer target type" #196. Closed PDowney opened this issue Aug 23, 2018 · 3 comments ... error: assignment discards 'const' qualifier from pointer target type [-Werror=discarded-qualifiers] ctx->in_buf->pos = ctx->zstream.next_in; ^

  12. const在指针赋值时候注意事项:assignment discards 'const' qualifier from pointer

    本文介绍了const在指针赋值时候的用法和注意事项,以及如何解决assignment discards 'const' qualifier from pointer target type的错误。文章给出了代码示例和解释,以及总结了const数据和非const数据的地址的赋值规则。

  13. C Warning

    Solution 1. You only have a const void* and assign that to a void*. Hence you can modify the target with pt_SAP->pt_param although you could not with pt_Param. This breaks the contract of the function parameter declaration, which "promises" not to modify the object to which pt_Param pointer. And hence the warning. Nice explanation, 5ed.

  14. Const Qualifier in C

    main.c: In function 'main': main.c:16:9: warning: assignment discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers] 16 | ptr = &j; | ^ *ptr: 10 *ptr: 20 3. Constant Pointer to Variable int* const ptr; The above declaration is a constant pointer to an integer variable, which means we can change the value of the ...

  15. warning: assignment discards qualifiers from pointer target type

    Here is basically what the code looks like: char *str; str = Inet_ntop (...); //returns const char * It's warning you that the "protection" of the pointer's target provided by the 'const' qualifier is lost when the 'const' is thrown away by assigning it to a "plain" type 'char*' pointer.

  16. warning: assignment discards 'const' qualifier from pointer target type#107

    warning: assignment discards 'const' qualifier from pointer target type #107. Closed osalbahr opened this issue Nov 22, 2023 · 2 comments ... assignment discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers] 1193 | hinfo = spec->gen.stream_analog_playback; | ^ At main.c:167: ...

  17. 解决 assignment discards 'const' qualifier from pointer target type 的问题

    本文介绍了如何解决编译时出现的 assignment discards 'const' qualifier from pointer target type 的警告,以及指针和 const 的用法和注意点。给出了一个外部库函数的例子,以及 const float *p, float *const p, const float *const p 三种指针定义的区别和用法。

  18. c

    When I try to use it like this I get a warning: warning: assignment discards 'const' qualifier from pointer target type [enabled by default]. So I'm confused. How can I retrieve the value I put into the cookie? Edit: I forgot to mention that I need to further process the data and want to make changes to it.

  19. video.c:63:22: error: assignment discards 'const' qualifier from

    Public signup for this instance is disabled.Go to our Self serve sign up page to request an account.