• CodeQL overview
  • Writing CodeQL queries
  • CodeQL query help documentation »
  • CodeQL query help for C# »

Useless assignment to local variable ¶

Click to see the query in the CodeQL repository

A value is assigned to a local variable, but either that variable is never read later on, or its value is always overwritten before being read. This means that the original assignment has no effect, and could indicate a logic error or incomplete code.

Recommendation ¶

Ensure that you check the program logic carefully. If a value is really not needed, consider omitting the assignment. Be careful, though: if the right-hand side has a side effect (like performing a method call), it is important to keep this to preserve the overall behavior.

The following example shows six different types of assignments to local variables whose value is not read:

In ParseInt , the result of the call to int.TryParse is assigned directly to the unread local variable success .

In IsDouble , the out argument of the call to int.TryParse is assigned to the unread local variable i .

In ParseDouble , the exception thrown by the call to double.Parse in case of parse failure is assigned to the unread local variable e .

In Count , the elements of ss are assigned to the unread local foreach variable s .

In IsInt , o is assigned (in case o is an integer) to the unread local type test variable i .

In IsString , o is assigned (in case o is a string) to the unread local type case variable s .

The revised example eliminates the unread assignments.

References ¶

Wikipedia: Dead store .

MSDN, Code Analysis for Managed Code, CA1804: Remove unused locals .

Microsoft: What’s new in C# 7 - Discards .

Common Weakness Enumeration: CWE-563 .

Sonar's Useless Assignment Error in Swift

Solving Sonar's 'Remove Useless Assignment of Local Variable' Error in Swift

Abstract: Learn how to resolve SonarQube's 'Remove Useless Assignment of Local Variable' error in Swift by understanding its cause and using different workarounds.

Solving Sonar's "Remove Useless Assignment to Local Variable" Error in Swift

Sonar is a popular tool used for code analysis and review. It helps developers identify and fix issues in their code, making it more readable, maintainable, and secure. One common issue that Sonar flags is the "Remove Useless Assignment to Local Variable" error in Swift. This error occurs when a local variable is assigned a value that is not used in the code. In this article, we will discuss how to solve this error in Swift.

Understanding the Error

To understand the error, let's consider an example:

In this example, we declare two local variables, x and y. We assign the value 5 to x and then calculate the value of y by multiplying x by 2. However, we never use the value of x again in the code. Therefore, Sonar flags the assignment of x as a useless assignment.

Solving the Error

To solve the error, we need to ensure that every local variable is used in the code. We can do this by either using the variable or removing its declaration. In the above example, we can remove the declaration of x, as it is not used in the code:

Alternatively, we can use the value of x in the code:

In this example, we print the value of x to the console, ensuring that it is used in the code.

Using Sonar to Identify Useless Assignments

Sonar can help us identify useless assignments in our code. To do this, we need to configure Sonar to analyze our Swift code. We can do this by installing the SonarSwift plugin and configuring it to analyze our project. Once we have done this, Sonar will flag any useless assignments in our code, allowing us to fix them.

The "Remove Useless Assignment to Local Variable" error in Swift is a common issue that Sonar flags. To solve this error, we need to ensure that every local variable is used in the code. We can do this by either using the variable or removing its declaration. Sonar can help us identify useless assignments in our code, allowing us to fix them and improve the quality of our code.

Remove Useless Assignment to Local Variable

Supported Languages

Tags: :  Swift SonarQube Software Development

Latest news

  • Issue Installing 32-bit Matplotlib in Python
  • Optimizing Memory Usage in Real-Time Data Processing with Python Pandas
  • Troubleshooting Hamburger Menu Implementation in Android Development
  • Setting User-Changed Variables in Python: Overwrite or Merge?
  • Adding a Consistent Footer to PDF Files in Software Development
  • Fixing Menu Glitches in Elementor v3.21: A Guide for Site Owners
  • Troubleshooting Expected Identifier Errors in BizTalk 2016 SFTP Integrations
  • Error: Item Key Already Added in HttpPost, setUSUARIO
  • Chasing Sand and Lizards: Weather Forecasts for Project Sites
  • Creating a Blazor Server App with DetailedErrors in Visual Studio
  • std::fstream::write() modifies tellg()?
  • Interacting with OllamaAPI: Handling Significant Response Messages
  • Implementing Recovery Codes in TOTP Multi-Factor Authentication: A Backup Solution
  • Errors Sending Request to API: Dolar Endpoint
  • Using LAG Function to Get Last 'Consume' Event in SQL for Product Units
  • Measuring Actual Indefiniteness: Understanding Undefined Behavior Memory Access in C's free() Call
  • Renaming Columns in Workbook View Control
  • Error in Reading Block 2 File during PostgreSQL Table Import
  • Custom Domain Blocked: Hosting Angular Application on GitHub Pages
  • Assigning Tasks with Google Forms: Performflow Integration
  • Writing OData Queries with Filter Property and Deep Expands
  • Making No One See Your Request Traffic with Python
  • NPMP Installation Taking Forever: Unable to Finish (Local PC and Docker)
  • Automating Birthday Wishes: Seeking Recommendations for a Free WhatsApp API
  • ImageField Django Forms Not Working: A Solution
  • Rules for Snake Wrestling Competition: Eligibility Criteria
  • Maintaining Unique Git Subtrees in Shopify: Best Practices
  • Suppressing Content Approval Status Change Signature in SharePoint Power Automate
  • Bunch of Things Keep Breaking in Unity: A Common UI Issue
  • Efficiently Reading Large Databases with Spring JPA and Stream: A Batch Processing Approach
  • Parsing JSON Output in PHP
  • Configuring Sphinx with Different Python Versions on RHEL8
  • Execution Failed: app: checkDebugAarMetadata (React Native CLI)
  • Understanding the Readelf R(--relocated-dump) Option: Contents Section Relocated Information
  • Implementing Consistent Hashing in Dynamic Microservices Architecture: Resolving Load Balancer Issues
Topic Replies Views Activity
Sonar Updates ,  , 

We have big news for our dear C and C++ SonarQube users. Configuring the analysis requires some skills; at times, it can get technical and tedious, with a few known caveats. We unleashed the talent of our mighty enginee…

3 237 June 20, 2024
SonarQube ,  ,  ,  1 31 June 28, 2024
SonarQube 0 17 June 28, 2024
SonarQube 4 87 June 28, 2024
SonarQube ,  ,  ,  1 24 June 28, 2024
SonarQube 0 21 June 28, 2024
SonarQube 5 106 June 28, 2024
SonarQube ,  ,  ,  0 19 June 28, 2024
SonarQube 6 14063 June 28, 2024
SonarQube ,  ,  2 49 June 27, 2024
SonarQube 0 26 June 27, 2024
Report False-positive / False-negative... 11 81 June 27, 2024
SonarQube 1 35 June 27, 2024
SonarQube 0 23 June 27, 2024
Product Manager for a Day 10 1614 June 27, 2024
SonarQube 8 568 June 27, 2024
Report False-positive / False-negative... 3 90 June 27, 2024
SonarQube 0 25 June 27, 2024
SonarQube 6 93 June 27, 2024
Product Manager for a Day 4 691 June 27, 2024
SonarQube 3 95 June 27, 2024
SonarQube 0 57 June 26, 2024
9.9 LTA Upgrade 5 130 June 26, 2024
SonarQube ,  ,  3 56 June 26, 2024
SonarQube 2 417 June 26, 2024
SonarQube 11 179 June 26, 2024
SonarQube 1 52 June 26, 2024
SonarQube 1 44 June 26, 2024
SonarQube 6 165 June 25, 2024
SonarQube ,  ,  0 33 June 25, 2024

remove this useless assignment to local variable sonar fix java

"Remove this useless assignment to local variable", but the assignment is not useless

petr.h...@iongroup.com's profile photo

[email protected]

Michael Gumowski's profile photo

Michael Gumowski

-- You received this message because you are subscribed to the Google Groups "SonarQube" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected] . To view this discussion on the web visit https://groups.google.com/d/msgid/sonarqube/0d998b34-fedc-4c60-82b6-171e9a4a1914%40googlegroups.com . For more options, visit https://groups.google.com/d/optout .

SonarLint : Unused local variables should be removed

SonarLint : Unused local variables should be removed

sandeep negi's photo

If there are some variables that are usually used by the developers for debugging but later those variables are not used. Those variables should be removed since it is a dead code.It will improve the maintainability and other developers will not wonder where this local variable is used.

Example from sonar lint

Noncompliant Code Example

Compliant solution.

  • 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.

Remove this useless assignment to local variable - sonarqube - using try catch

In the following code, sonarqube is complaining for the mentioned error in the question:

How can I re-write this code to resolve this complain from sonarqube?

teenup's user avatar

  • 1 Does your catch block rethrow? Can you provide a minimal reproducible example example rather then just commented bits? –  Jon Skeet Commented Nov 25, 2020 at 11:15
  • @Jon I have provided the exact code. –  teenup Commented Nov 25, 2020 at 11:17
  • 1 Have you tried not having a result at all and doing a return await func() / return default(T) instead? –  Caius Jard Commented Nov 25, 2020 at 11:18
  • 2 I could assume that it's complaining about T result = default; but why are you making me guess? –  Damien_The_Unbeliever Commented Nov 25, 2020 at 11:19
  • 1 @TimSchmelter: How is it redundant? If func() throws an exception or the task it returns throws an exception, there'd be no value in result . Without the initial assignment, the variable isn't definitely assigned at the return statement. –  Jon Skeet Commented Nov 25, 2020 at 11:19

Know someone who can answer? Share a link to this question via email , Twitter , or Facebook .

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 .

Browse other questions tagged c# sonarqube or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Should we burninate the [lib] tag?
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Reconstructing Euro results
  • How can these passive RLC circuits change a sinusoid's frequency?
  • How to bid a very strong hand with values in only 2 suits?
  • Can I tell a MILP solver to prefer solutions with fewer fractions?
  • Do countries at war always treat each other's diplomats as personae non gratae?
  • DSP Puzzle: Advanced Signal Forensics
  • Can a planet have a warm, tropical climate both at the poles and at the equator?
  • What kind of sequence is between an arithmetic and a geometric sequence?
  • Algorithm to evaluate "connectedness" of a binary matrix
  • Did James Madison say or write that the 10 Commandments are critical to the US nation?
  • Does Not(A and not-A) = Not(A nand A) in intuitionistic logic?
  • George Martin story about a war in which he mentions airplanes called Alfies (meaning Alphas, I think)
  • Why are there no Goldstone modes in superconductor?
  • Synthesis of racemic nicotine
  • Do I need a foundation if I want to build a shed on top of paved concrete area?
  • Could a transparent frequency-altering material be possible?
  • Cleaning chain a few links at a time
  • Co-authors with little contribution
  • Drawing waves using tikz in latex
  • What actual purpose do accent characters in ISO-8859-1 and Windows 1252 serve?
  • Is physics limited to smooth sets?
  • How can I take apart a bookshelf?
  • Trying to determine what this item is
  • Were there engineers in blimp nacelles, and why were they there?

remove this useless assignment to local variable sonar fix java

IMAGES

  1. Remove this useless assignment to local variable Sonarqube

    remove this useless assignment to local variable sonar fix java

  2. Solución (FIX): Sonar

    remove this useless assignment to local variable sonar fix java

  3. Sonar: Remove this useless assignment to variable "locale" · Issue

    remove this useless assignment to local variable sonar fix java

  4. javascript

    remove this useless assignment to local variable sonar fix java

  5. How to convert JSON String to java object

    remove this useless assignment to local variable sonar fix java

  6. Sonar: Remove this useless assignment to variable "locale" · Issue

    remove this useless assignment to local variable sonar fix java

VIDEO

  1. Enable HyperOS new feature "Remove useless apps and make device smooth" #shorts

  2. How To Fix Java Exception Has Occurred in 2024

  3. useless bhawra #youtube #youtubeshorts #shorts #trending

  4. Remove useless object in photoshop #adobephotoshop #backgroundremover #graphicdesign #fyp #trending

  5. Remove Useless Part From Life || Real Words #selfimprovement #motivation #confidence #shorts

  6. Getting Rid Of Unused Variables (Finally)

COMMENTS

  1. SonarQube displaying to 'remove this useless assignment to local variable'

    It's best to avoid reassignment whenever possible, and it's almost always possible to avoid reassignment. If you need another variable that contains a ValidateAddressRequest, give it a different variable name so that you can use const to declare both variables; that makes the code more understandable at a glance, when a reader can be sure that a particular variable reference isn't ever going ...

  2. Sonar "useless assignment to local variable" workaround?

    Note that this would also be an issue if the initial assignment was something other than null. Unless the right-hand-side of the assignment has a side effect, any assignment is wasted. (Sonar analyses for side-effects) This is suspicious to Sonar: Maybe the programmer expected the first assignment to have an effect -- it doesn't, so perhaps it ...

  3. Sonarlint wrong "useless assignment to local variables"

    intellij, java. Philippe_Cade (Philippe Cadé) May 7, 2020, 8:45am 1. Since the last update of Sonarlint, we now have some obviously wrong issues reported about useless assignments to local variables: 990×328 25 KB. I think this only happens in standalone mode, when connected to Sonar those issues are not shown.

  4. S1854 FP

    Make sure to read this post before raising a thread here: Then tell us: Java SonarQube v10.5.1 Indicates useless assignment to 'METHOD' private static void rollbackOrCommit(DBConnection theDB) { final String ME…

  5. S1854 Remove this useless assignment to a local variable, when used in

    A false positive is generated when the variable is only used in a range operator. versions used : Sonarlint 4.23.0.19399 Visual Studio 2019 Community Edition 16.6.4 c# minimal code sample to reproduce: var prepTexts = "From here"; var test = prepTexts.IndexOf(" ", StringComparison.Ordinal)+1; //hits S1854 Remove this useless assignment to local variable var res= prepTexts[test..9]; //when the ...

  6. "Remove this useless assignment to local variable" doesn't ...

    StructA a = aFunctionThatReturnsStructA(args); // Remove this useless assignment to local variable a StructB b = {.field1 = a.field1}; The text was updated successfully, but these errors were encountered:

  7. "Remove this useless assignment to local variable", but the assignment

    Hello. In the following code: attemptNumber++; } catch (IOException e) {. System. exit ( 1 ); Sonar warns me that the line "attemptNumber++" is a useless assignment. However, the value is being read -- in the reachable catch block. Best regards, Petr.

  8. SonarQube displaying to 'remove this useless assignment to local variable'

    On the first line of the if block, you assign to validateAddressRequest, but then on the third line of the if block, you overwrite validateAddressRequest without having read the previously assigned variable. So the first line is useless.

  9. Sonar: Remove this useless assignment to variable "locale" #12472

    Sonar: Remove this useless assignment to variable "locale" #12472. Closed 1 task done. qmonmert opened this issue Sep 10, 2020 · 3 comments · Fixed by #12504. ... Launch analysis ./mvnw -Pprod clean verify sonar:sonar; Related issues Suggest a Fix. Delete the line locale = TranslatorContext.context.locale; JHipster Version(s) Current version.

  10. S1481 False Positive "Remove this useless assignment to local variable

    Find and fix vulnerabilities Codespaces. Instant dev environments ... carldebilly changed the title S1481 False Positive S1481 False Positive "Remove this useless assignment to local variable 'x'" Feb 28, 2020. ... Remove this useless assignment to local variable S1854. We have Sonar Version 8.3.1 (build 34397) and C# plugin 8.6.1 (build 17183)

  11. Remove this useless assignment to variable

    I am using SimpleDataTables JS Library and their minimal suggested implementation: const dataTable = new DataTable("#myTable"); In SC this throws me an Remove this useless assignment to variable "dataTable". and an Remove the declaration of the unused 'dataTable' variable. If I remove the assignement SC tells me to Either remove this useless object instantiation of "DataTable" or use it. In SC ...

  12. Useless assignment to local variable

    In IsDouble, the out argument of the call to int.TryParse is assigned to the unread local variable i. In ParseDouble, the exception thrown by the call to double.Parse in case of parse failure is assigned to the unread local variable e. In Count, the elements of ss are assigned to the unread local foreach variable s.

  13. False Positive useless assignment to local variable #3115

    False Positive useless assignment to local variable #3115. Closed Dixtosa opened this issue Feb 12, 2020 · 1 comment ... The warning is "remove this useless assignment to local variable". Known workarounds. ... this fix for #3094 is on master and will be in the next release. All reactions.

  14. Solving Sonar's 'Remove Useless Assignment of Local Variable' Error in

    Using Sonar to Identify Useless Assignments. Sonar can help us identify useless assignments in our code. To do this, we need to configure Sonar to analyze our Swift code. We can do this by installing the SonarSwift plugin and configuring it to analyze our project. Once we have done this, Sonar will flag any useless assignments in our code ...

  15. Topics tagged sonarqube

    Sonar Updates. sonarqube, cfamily, ... S1854 FP - Remove this useless assignment to local variable. Report False-positive / False-negative... sonarqube. 11: 67: June 27, 2024 ... java, sonarqube, coverage. 2: 82: June 25, 2024 Remove this unused method parameter reported when method called via method reference only ...

  16. "Remove this useless assignment to local variable", but the assignment

    All groups and messages ... ...

  17. SonarLint : Unused local variables should be removed

    Those variables should be removed since it is a dead code.It will improve the maintainability and other developers will not wonder where this local variable is used. Example from sonar lint. int seconds = 0; // seconds is never used return hours * 60; return hours * 60;

  18. S1854 False Positive useless assignment to local variable #2760

    The warning S1854 should not be thrown in the case that a variable is set a value, and might be updated in a try/catch block. Repro steps. See the following code. The warning is raised about the variable ports.

  19. c#

    SONAR Issue "Method parameters, caught exceptions and foreach variables should not be reassigned" ... remove this useless assignment to local variable c#. 0 ... Sonar issue - Remove this useless assignment to local variable. 3 SonarQube null pointers should not be dereferenced on try/catch. 1 Sonarqube - Catches should be combined ...