• Install App

New to Java

For appeals, questions and feedback about Oracle Forums, please email [email protected] . Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

The assignment to variable x has no effect

the assignment to variable name has no effect

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

Java中有关this的一个问题

the assignment to variable name has no effect

先看这样一个简单的程序:

很显然,输出结果是3.

但如果我把构造器中的this去掉呢?即,将程序改为:

程序能否编译通过?结果又是多少?

运行之后发现,编译能够通过,而且输出结果是1.

我们注意到系统给出了一个警告:"The assignment to variable i has no effect."

这个警告说明了构造器中的“i=i”是个毫无意义的语句。

经过debug发现,在对象ct创建时,构造器中的语句没有起到任何作用,对于i的赋值直接采用的是默认值1.

如果传入参数的名称和域变量的名称相同,则必须用this来指明域变量,否则编译器将认为语义不清,从而调用其默认值。

这个问题看似简单,但如果我们在平时的编程中稍有不注意,也是很容易犯这样的错误的。

the assignment to variable name has no effect

请填写红包祝福语或标题

the assignment to variable name has no effect

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

the assignment to variable name has no effect

Uploaded image for project: 'JDK'

  • JDK-8289381

Fix warnings: The assignment to variable has no effect

the assignment to variable name has no effect

  • Resolution: Fixed

the assignment to variable name has no effect

  • Fix Version/s: jfx19
  • Affects Version/s: jfx19
  • Component/s: javafx
  • noreg-cleanup
  • Subcomponent: build

Description

Attachments, issue links.

Task - A task that needs to be done.

Java Certification Resources and Java Discussion Forum

Skip to content

  • Java Certification Board index Discussion Forum OCA OCP Java Programmer Certification Questions Discussion

Variable Assignment Having No Effect

Moderator: admin

Post by Sweetpin2 » Thu Feb 21, 2013 3:30 pm

Re: Variable Assignment Having No Effect

Post by admin » Thu Feb 21, 2013 6:49 pm

Return to “OCA OCP Java Programmer Certification Questions Discussion”

  • Discussion Forum
  • ↳   OCFA Java Foundations Certified Junior Associate Questions
  • ↳   OCA OCP Java Programmer Certification Questions Discussion
  • ↳   Servlet/JSP Web Component Developer Certification (SCWCD/OCE-WCD/OCWCD) 1Z0-899/1Z0-858
  • ↳   EJB/JPA Certification (SCBCD/OCE-JPA/OCE-EJBD) 1Z0-895/1Z0-898
  • ↳   Java Web Services Developer Certification (OCE-JWS) 1Z0-897
  • ↳   Other Certifications
  • ↳   Time Pass Lounge
  • ↳   Feedback, Suggestions, Comments, Admin Communication
  • ↳   General Java Discussion
  • ↳   Errors/Bugs that have been fixed

Who is online

Users browsing this forum: No registered users and 1 guest

  • All times are UTC-05:00
  • Delete cookies

Powered by phpBB ® Forum Software © phpBB Limited

Style proflat by © Mazeltof 2017

Privacy | Terms

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

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

Setting the variable $USERNAME has no effect

Setting the variable USERNAME has no effect. Accessing the variable always returns the current logged in user.

I could not find any reference or documentation that explains this behaviour. It seems as if $USERNAME is some kind of special variable. Are there others? Where is this documented or explained?

  • environment-variables

James's user avatar

  • 1 not reproduced here. what shell are you on? –  把友情留在无盐 Commented Mar 31, 2015 at 9:05

2 Answers 2

It seems you are using the Z Shell , at least the behavior you are describing is reproducible there:

The manpage zshparam gives the reason:

USERNAME The username corresponding to the real user ID of the shell process. If you have sufficient privileges, you may change the username (and also the user ID and group ID) of the shell by assigning to this parameter. Also (assuming sufficient privileges), you may start a single command under a different username (and user ID and group ID) by `(USERNAME=username; command)'

So, with sufficient privileges, e.g. as root this works, but only if user1 is a valid username:

And yes, there are other special variables, look out for the <S> marking in man zshparam , only to mention a few examples:

  • $? exit status returned by the last command
  • $$ process ID of this shell
  • $EGID effective group ID of the shell process
  • $SECONDS number of seconds since shell invocation
  • This really is a zsh thing. I just recently switched to zsh and it took us quite a while to understand why our script did not run as expected anymore because the script uses a variable called USERNAME... :-| –  James Commented Mar 31, 2015 at 12:03
  • @James: You should spend your script a #!/bin/bash shebang line ;) -- except it must be sourced . –  mpy Commented Mar 31, 2015 at 12:31
  • I'll definitively will add the shebang line! –  James Commented Mar 31, 2015 at 12:41

USER and LOGNAME are addressed in envron(7) manpage. login(1) is the process who set these variables .

both USER and LOGNAME variables can be modified and later access return the new value.

find nowhere the reference for USERNAME, and this variable is not set in bash4.3. bash defines a UID readonly numerical variable. attempt to change this variable in bash fails.

linux manpage says USER "is used by some BSD-derived programs" while LOGNAME "is used by some System-V derived programs" and apple manpage claim USER deprecated.

把友情留在无盐's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged shell zsh environment-variables ..

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • Plausible orbit to have a visible object slowly circle over the night sky
  • Is reading sheet music difficult?
  • What do these expressions mean in NASA's Steve Stitch's brief Starliner undocking statement?
  • "With" as a function word to specify an additional circumstance or condition
  • What is the least number of colours Peter could use to color the 3x3 square?
  • Flats on gravel with GP5000 - what am I doing wrong?
  • What are the steps to write a book?
  • What was the typical amount of disk storage for a mainframe installation in the 1980s?
  • Would it be out of style to start a history book with a poem I wrote?
  • Does Gödel’s incompleteness theorems imply the necessity of an infinite recursive hierarchy of “proofs”, and that any “proof” is relative?
  • How can I add a neutral to a 240V to 120V circuit conversion?
  • Understanding the parabolic state of a quantum particle in the infinite square well
  • is it possible to add a stepwise counter for assigning a number to each text block?
  • What is the Kronecker product of two 1D vectors?
  • Why a minus sign is often put into the law of induction for an inductor
  • On the convex cone of convex functions
  • Which volcano is more hazardous? Mount Rainier or Mount Hood?
  • How to simplify input to a table with many columns?
  • What was IBM VS/PC?
  • Pólya trees counted efficiently
  • How to fold or expand the wingtips on Boeing 777?
  • Are fuel efficiency charts available for mainstream engines?
  • Why does each leg of my 240V outlet measure 125V to ground, but 217V across the hot wires?
  • Is the 2024 Ukrainian invasion of the Kursk region the first time since WW2 Russia was invaded?

the assignment to variable name has no effect

  • Learn Python: From Beginner to Professional
  • About iPython.com
  • Privacy Policy
  • Introduction to Python
  • Python Setup & Environment
  • Syntax and Basics
  • Control Structures
  • Syntax Break
  • Quizzes & Tests

Python Variable Naming: Rules, Conventions, and Best Practices

Python Variable Naming Guide – Best Practices and Tips

Enhance your Python programming with effective variable naming techniques.

Introduction

In Python, as in any programming language, naming variables is a fundamental skill. Effective variable naming enhances code readability and maintainability. This post dives deep into the rules, conventions, and best practices for naming variables in Python, offering examples and tips to avoid common pitfalls.

What Are Variables in Python?

Variables are like containers for storing data values. In Python, a variable is created the moment you first assign a value to it.

Python Variable Naming Rules

  • Case Sensitive: Python variables are case sensitive. This means Age , age , and AGE are three different variables.
  • Start with Letter or Underscore: Variables must start with a letter (A-Z/a-z) or an underscore (_).Example: _name , userAge
  • Contain Alphanumeric and Underscores: After the first letter, a variable name can contain letters, numbers, and underscores.Example: data2 , user_id
  • Avoid Python Keywords: Variables should not use Python reserved words like False , True , if , else , etc.

Naming Conventions

  • Snake Case (Preferred in Python): Variables should be lowercase with words separated by underscores.Example: student_name , total_price
  • Camel Case: Start with a lowercase letter and capitalize the first letter of each subsequent word.Example: studentName , totalPrice
  • Pascal Case: Similar to Camel Case, but the first letter is also capitalized.Example: StudentName , TotalPrice

Best Practices and Tips

  • Descriptive Names: Choose meaningful names that convey the purpose of the variable.Bad: a , var1 , x Good: student_age , total_items , file_path
  • Length of Names: Keep the variable name concise yet descriptive.Example: num (short for number), not n or number_of_items
  • Avoid Ambiguity: Use clear and unambiguous terms.Example: Instead of data , use customer_data or product_data .
  • Consistency: Be consistent with naming conventions throughout your code.

Common Mistakes

  • Using Digits at the Start: Variables should not begin with a digit.Incorrect: 1_record Correct: record1
  • Confusing l, O, I with 1, 0: Avoid using l (lowercase L), O (uppercase o), and I (uppercase i) as they can be confused with 1 and 0 .
  • Overly Short or Verbose Names: Avoid names that are too short to be meaningful or too long to be readable.

Adhering to these rules and conventions for naming variables in Python not only makes your code more readable but also more maintainable. Remember, the code you write is not just for machines to execute, but for humans to read and understand. Embrace these practices to become a more effective Python programmer.

Assignment: Python Variable Naming Exercise:

This practical assignment is designed to reinforce your understanding of Python variable naming conventions and best practices. Apply your knowledge by correcting variable names and creating your own! This assignment not only allows you to practice variable naming but also helps in understanding why it is a critical aspect of programming. Submit your answers and reflections in the comments below to deepen your comprehension of Python coding standards!

Part 1: Correcting Variable Names

Task: Below are some poorly named Python variables. Correct each one following Python’s naming conventions and best practices.

  • 2ndPlaceWinner
  • total#ofBooks

Part 2: Creative Variable Naming

Task: Create descriptive variable names for the following descriptions. Follow Python’s naming conventions.

  • The age of a user.
  • The title of a blog post.
  • The total amount in a shopping cart.
  • The number of files downloaded.
  • The status of a server connection.

Part 3: Reflection

Task: Reflect on why good variable naming is important in programming. Write a short paragraph about how the principles of effective variable naming can improve code readability and maintenance.

Test Your Understanding of Python Variable Naming

This quiz is designed to test your knowledge of Python's variable naming rules, conventions, and best practices. Challenge yourself and solidify your understanding!

In Python, variable names are case-sensitive.

Why should you avoid using l and O as variable names in Python?

Which of the following is a valid Python variable name?

Which of the following is NOT a Python naming convention?

Which of the following is a recommended practice for variable names?

Are underscores ( _ ) allowed in Python variable names?

Which naming convention is typically used and recommended in Python?

Your score is

The average score is 88%

Restart quiz

Previous Comments in Python: Enhancing Readability and Maintainability

Next understanding data types in python: a comprehensive guide, related posts ....

Advanced Synchronization Primitives in Python

Advanced Synchronization Primitives in Python: Beyond Locks

Python Thread Pool Example using concurrent.futures

Leveraging Thread Pools in Python: A Guide to ThreadPoolExecutor

Advanced Python list comprehensions concept with nested structures, mathematical symbols, and code snippets, illustrating depth and complexity.

Advanced List Comprehensions in Python: Beyond the Basics

Abstract visualization of NoneType in Python, symbolizing the absence of value with Python code elements.

Introduction to NoneType and Its Usage in Python Programs

Leave a reply cancel reply.

You must be logged in to post a comment.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Assignment (=)

The assignment ( = ) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

A valid assignment target, including an identifier or a property accessor . It can also be a destructuring assignment pattern .

An expression specifying the value to be assigned to x .

Return value

The value of y .

Thrown in strict mode if assigning to an identifier that is not declared in the scope.

Thrown in strict mode if assigning to a property that is not modifiable .

Description

The assignment operator is completely different from the equals ( = ) sign used as syntactic separators in other locations, which include:

  • Initializers of var , let , and const declarations
  • Default values of destructuring
  • Default parameters
  • Initializers of class fields

All these places accept an assignment expression on the right-hand side of the = , so if you have multiple equals signs chained together:

This is equivalent to:

Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5 , and x is initialized with the value of the y = 5 expression, which is also 5 . If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode , or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:

Simple assignment and chaining

Value of assignment expressions.

The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.

Unqualified identifier assignment

The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global. .

Because the global object has a String property ( Object.hasOwn(globalThis, "String") ), you can use the following code:

So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String ; you can just type the unqualified String . To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.

In strict mode , assignment to an unqualified identifier in strict mode will result in a ReferenceError , to avoid the accidental creation of properties on the global object.

Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

Assignment with destructuring

The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.

For more information, see Destructuring assignment .

Specifications

Specification

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Assignment operators in the JS guide
  • Destructuring assignment

How to resolve -W0104: Statement seems to have no effect (pointless-statement)

Abstract: Learn how to resolve the -W0104 warning in your code. This warning indicates that a statement in your code seems to have no effect and is considered a pointless statement. Find out how to identify and fix these statements to improve code efficiency and readability.

How to Resolve -W0104: Statement Seems to Have No Effect (pointless-statement)

If you are a software developer, you might have come across the warning message "-W0104: Statement seems to have no effect (pointless-statement)" while working on your code. This warning is usually issued by static code analysis tools, such as linters, to indicate that a particular statement in your code does not have any effect and can be safely removed. Although it might seem like a minor issue, it is important to address these warnings as they can lead to confusion, increase code complexity, and potentially introduce bugs. In this article, we will explore the common causes of this warning and discuss how to resolve it.

Causes of -W0104 Warning

There are several reasons why you might encounter the -W0104 warning:

  • Unused variables: If you declare a variable but never use it, the statement assigning a value to that variable becomes pointless. For example:
  • Unused return values: If you call a function that returns a value but do not use that value, the statement becomes pointless. For example:
  • Unused expressions: If you have an expression that does not have any side effects or is not used in any meaningful way, the statement becomes pointless. For example:

Resolving the Warning

To resolve the -W0104 warning, you should carefully review the code and determine whether the statement in question is indeed unnecessary. Here are a few strategies to address this warning:

  • Remove the statement: If the statement is truly pointless and does not contribute to the functionality of your code, you can safely remove it. However, make sure to double-check that removing the statement does not introduce any unintended consequences.
  • Refactor the code: If the statement is part of a larger block of code, consider refactoring it to eliminate the need for the pointless statement. Sometimes, a seemingly pointless statement can be a result of incomplete code or a leftover from previous iterations.
  • Use the statement: If the statement serves a purpose but is mistakenly identified as pointless, you can explicitly use the value or assign it to a variable to indicate its intended use. This can help clarify the code and prevent the warning from being raised.

The -W0104 warning, indicating a statement that seems to have no effect, should not be ignored in your code. By addressing these warnings, you can improve code readability, reduce confusion, and minimize the risk of introducing bugs. Take the time to review and resolve these warnings as part of your software development process, and you will be on your way to writing cleaner and more maintainable code.

References
Title Link
Static code analysis tools
Code refactoring

Tags: :  exception testing pylint

Latest news

  • Creating an Edit Button and Form for Your Software Development Site
  • SQL Criteria: Pulling Repair Orders with Single Rows
  • Boosting Efficiency with Hazelcast's executeOnKeys and Smart Routing
  • Making React: use-AntDesign's DatePicker.RangePicker Display Inline Calendars
  • Resolving NodaTime Binding Issues with Local Datetime in ASP.NET Core Razor Pages
  • Scaling Y-axis Continuously: Making Your Bar Chart Go Missing
  • Unexpected Results with Azure AI Search: Fuzzy Search and Hyphens
  • Implementing Text Formatting in an Android Note App: Bold and Italic
  • Flattening Lists in Specific Way: A Solution to Common Struggles
  • Forcing HTTPS in a ViteKit App Deployed on Heroku
  • Automatically Updating Google Sheets: A Guide to Moving Rows with IMPORTRANGE
  • Switching Different API Calls at Runtime using Apollo/Angular QueryRef: A Practical Example
  • Automatically Loading JSON Files in Specific Folders for a React Project
  • Understanding Power BI Pro License Dataset Storage Limits
  • Boosting Your Resume: Adding Tools and Technologies Used in Past Projects
  • Understanding 'Invalid Operation: Multisampled Framebuffer' in WebGL2
  • Azure ServiceBus Messaging: Handling ServiceBusException with io.cloudevents in Apache Camel
  • Sending JSON Data to Kafkatopic using Telegraf: Format Mismatch
  • Recording the First-Time Event in a 4-State Markov Chain: Simulating Hospital Patients
  • Accessing Cloud9 from a Private Network: A Step-by-Step Guide
  • Using `ctypes.get_errno()` for Error Handling in C Type Libraries
  • Renaming Columns Based on Simple Condition using JOIN in Software Development
  • Building an Azure IoT Hub SDK Swift iOS App: Connect and Listen for Cloud Messages
  • Error with 'filter' function in Shiny: Extracted numbers lead to incorrect arguments
  • Troubleshooting Rendered Buttons on Software Development Pages: A 6-Attempt Solution
  • Tackling a Talend Issue: Job Construction Failed to Initialize a Class in AWS Athena Connection
  • Extracting Key-Appended Message Values with Kafka Connect
  • Python Integration with C++Builder: Creating AES-256 File Encryption Project using Argon2 and CLI commands
  • Ajax Form Handling Problem in Work MVC: Embedded Ajax Call
  • Upgrading Spring Boot 3.1.9 to 3.2.2: Handling 'UnsupportedOperationException' with LogbookHttpRequestInterceptor and ApacheHttpClient 5
  • Constructing Dynamic Statements: Possible with Graph Traversal?
  • Testing PowerShell Desired State Configuration (DSC) Extension on Azure Arc-enabled Servers
  • Grouping Numbers in Powershell: A Comprehensive Guide
  • Understanding Mutable and Immutable Objects in Python: A Realization
  • Avoiding Switch-Case Statements in C#: Dependency Considerations

Go to list of users who liked

More than 1 year has passed since last update.

the assignment to variable name has no effect

eclipse警告"assignment to variable xxx has no effect"についての覚書き

ええと、入門者向けテストにありがちなクイズだと思いますが、以下のJavaコードがあった時、aが増えないステートメントはA~Fのどれでしょうか。

正解はBですね。Javaの仕様では、上記のうちBの文a=a++;のみ、aのインクリメントが意味を持ちません。後置インクリメントa++は代入操作の後に行われることになっていますが、代入先もaなので、インクリメント前の値でアサインが完了してしまい、文の判定としてはインクリメント前のaに戻される(もともとのaが残る)ことになります。上記の実行結果は以下。

eclipseWarning2.png

まず、この警告メッセージ、「変数への代入(アサインメント)の効果が無い」と言っているのであって、その文(ステートメント)に効果が無いと言っているわけではありません。代入に意味があるか、それ無しで結果が同じかがポイントなわけです。Eのa=++a;は、++a;と同じように1増える。つまり「a=」は無意味なので警告が出る。逆に、Bのa=a++;は、a++;と同じではない。文は結果としてaを変えないが、代入にはインクリメントを無効化する効果がある。なので、Bは警告が出ないのが正しい。・・・いや、考えたらその通りなんですけどね。詳しい方は「当たり前だろ」と思ってるかもしれません。

いちおう、eclipseの気持ちを確認するために、以下のように書き換えてみました。

eclipseの言いたいことは、volatile宣言した変数cを見ると、更に明確になります。上記のうち、G(c=++c;)はE(a=++a;)と同じ前置インクリメント後の代入なのに警告が出ません。代入操作(c=と書くこと)に、コンパイラにとってのキャッシュ制御上の意味がある(かもしれない)からです。「=」が無駄なら警告が出るし、何らかのエフェクトがあれば出ないという基準が再確認できます。なお、このvolatile宣言時の規定については、2010年頃にeclipse仕様が修正される前の掲示板のやりとり(BUG 310264)を確認することができました。

また、上記コード、mainメソッドではなく引数:int dのコンストラクタに書き換えているのですが、H(d=d;)とI(this.d=d;)についてはどうでしょうか。当然のように、Hには警告が出てくれました。恐らくですが、この警告のメインターゲットは、このthis.d=d;をd=d;と誤って書いてしまうケースなのではないでしょうか。割と起こりえるミスなので、やはり、この警告の存在自体は助かります。逆に、私が勝手に混乱していたB(a=a++;)とE(a=++a;)のようなコードは、冒頭のクイズ問題のような例外的ケースでしか書くことがないでしょう。

今回は、少し検索すれば出てくるような内容なので、ちょっとネタとしては微妙だったかもしれません。ただ、volatileの話と警告の意義(this抜け防止)を含めて書くと意味があるかもと思ったので・・・。以上、覚書きでした。

Go to list of comments

Register as a new user and use Qiita more conveniently

  • You get articles that match your needs
  • You can efficiently read back useful information
  • You can use dark theme

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python - variable names, variable names.

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)
  • A variable name cannot be any of the Python keywords .

Legal variable names:

Illegal variable names:

Remember that variable names are case-sensitive

Advertisement

Multi Words Variable Names

Variable names with more than one word can be difficult to read.

There are several techniques you can use to make them more readable:

Each word, except the first, starts with a capital letter:

Pascal Case

Each word starts with a capital letter:

Each word is separated by an underscore character:

Video: Python Variable Names

Python Tutorial on YouTube

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

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

What is the benefit of having the assignment operator return a value?

I'm developing a language which I intend to replace both Javascript and PHP. (I can't see any problem with this. It's not like either of these languages have a large install base.)

One of the things I wanted to change was to turn the assignment operator into an assignment command, removing the ability to make use of the returned value.

I know that this would mean that those one-line functions that C people love so much would no longer work. I figured (with little evidence beyond my personal experience) that the vast majority of times this happened, it was really intended to be comparison operation.

Or is it? Are there any practical uses of the assignment operator's return value that could not be trivially rewritten? (For any language that has such a concept.)

  • language-agnostic

billpg's user avatar

  • 12 JS and PHP do not have a large "install base"? –  mhr Commented Feb 13, 2014 at 12:33
  • 47 @mri I suspect sarcasm. –  Andy Hunt Commented Feb 13, 2014 at 12:41
  • 12 The only useful case I can remember is while((x = getValue()) != null) {} . Replacements will be uglier since you'll need to either use break or repeat the x = getValue assignment. –  CodesInChaos Commented Feb 13, 2014 at 13:04
  • 12 @mri Ooh no, I hear those two languages are just trivial things without any significant investment at all. Once the few people who insist on using JS see my language, they will switch over to mine and never have to write === again. I'm equally sure the browser makers will immediately roll out an update that includes my language alongside JS. :) –  billpg Commented Feb 13, 2014 at 14:58
  • 4 I would suggest to you that if your intention is to enhance an existing language and you intend it to be adopted widely then 100% backwards compatibility with the existing language is good. See TypeScript as an exemplar. If your intention is to provide a better alternative to an existing language then you have a much harder problem. A new language has to solve an existing realistic problem much much better than the existing language in order to pay for the cost of switching. Learning a language is an investment and it needs to pay off. –  Eric Lippert Commented Feb 13, 2014 at 18:57

9 Answers 9

Technically, some syntactic sugar can be worth keeping even if it can trivially be replaced, if it improves readability of some common operation. But assignment-as-expression does not fall under that. The danger of typo-ing it in place of a comparison means it's rarely used (sometimes even prohibited by style guides) and provokes a double take whenever it is used. In other words, the readability benefits are small in number and magnitude.

A look at existing languages that do this may be worthwhile.

  • Java and C# keep assignment an expression but remove the pitfall you mention by requiring conditions to evaluate to booleans. This mostly seems to work well, though people occasionally complain that this disallows conditions like if (x) in place of if (x != null) or if (x != 0) depending on the type of x .
  • Python makes assignment a proper statement instead of an expression. Proposals for changing this occasionally reach the python-ideas mailing list, but my subjective impression is that this happens more rarely and generates less noise each time compared to other "missing" features like do-while loops, switch statements, multi-line lambdas, etc.

However, Python allows one special case, assigning to multiple names at once: a = b = c . This is considered a statement equivalent to b = c; a = b , and it's occasionally used, so it may be worth adding to your language as well (but I wouldn't sweat it, since this addition should be backwards-compatible).

  • 5 +1 for bringing up a = b = c which the other answers do not really bring up. –  Leo Commented Feb 13, 2014 at 15:53
  • 6 A third resolution is to use a different symbol for assignment. Pascal uses := for assignment. –  Brian Commented Feb 13, 2014 at 19:08
  • 6 @Brian: Indeed, as does C#. = is assignment, == is comparison. –  Marjan Venema Commented Feb 13, 2014 at 19:47
  • 3 In C#, something like if (a = true) will throw a C4706 warning ( The test value in a conditional expression was the result of an assignment. ). GCC with C will likewise throw a warning: suggest parentheses around assignment used as truth value [-Wparentheses] . Those warnings can be silenced with an extra set of parentheses, but they are there to encourage explicitly indicating the assignment was intentional. –  Bob Commented Feb 13, 2014 at 22:27
  • 2 @delnan Just a somewhat generic comment, but it was sparked by "remove the pitfall you mention by requiring conditions to evaluate to booleans" - a = true does evaluate to a Boolean and is therefore not an error, but it also raises a related warning in C#. –  Bob Commented Feb 13, 2014 at 23:48
Are there any practical uses of the assignment operator's return value that could not be trivially rewritten?

Generally speaking, no. The idea of having the value of an assignment expression be the value that was assigned means that we have an expression which may be used for both its side effect and its value , and that is considered by many to be confusing.

Common usages are typically to make expressions compact:

has the semantics in C# of "convert z to the type of y, assign the converted value to y, the converted value is the value of the expression, convert that to the type of x, assign to x".

But we are already in the realm of impertative side effects in a statement context, so there's really very little compelling benefit to that over

Similarly with

being a shorthand for

Again, in the original code we are using an expression both for its side effects and its value, and we are making a statement that has two side effects instead of one. Both are smelly; try to have one side effect per statement, and use expressions for their values, not for their side effects.

I'm developing a language which I intend to replace both Javascript and PHP.

If you really want to be bold and emphasize that assignment is a statement and not an equality, then my advice is: make it clearly an assignment statement .

There, done. Or

or even better:

Or even better still

There's absolutely no way that any of those are going to be confused with x == 1 .

Eric Lippert's user avatar

  • 1 Is the world ready for non-ASCII Unicode symbols in programming languages? –  billpg Commented Feb 14, 2014 at 11:25
  • As much as I would love what you suggest, one of my goals is that most "well written" JavaScript can be ported over with little or no modification. –  billpg Commented Feb 14, 2014 at 11:44
  • 2 @billpg: Is the world ready ? I don't know -- was the world ready for APL in 1964, decades before the invention of Unicode? Here's a program in APL that picks a random permutation of six numbers out of the first 40: x[⍋x←6?40] APL required its own special keyboard, but it was a pretty successful language. –  Eric Lippert Commented Feb 14, 2014 at 15:17
  • @billpg: Macintosh Programmer's Workshop used non-ASCII symbols for things like regex tags or redirection of stderr. On the other hand, MPW had the advantage that the Macintosh made it easy to type non-ASCII characters. I must confess some puzzlement as to why the US keyboard driver doesn't provide any decent means of typing any non-ASCII characters. Not only does Alt-number entry require looking up character codes--in many applications it doesn't even work. –  supercat Commented Feb 14, 2014 at 18:20
  • Hm, why would one prefer to assign "to the right" like a+b*c --> x ? This looks strange to me. –  Ruslan Commented Aug 21, 2015 at 10:49

Many languages do choose the route of making assignment a statement rather than an expression, including Python:

and Golang:

Other languages don't have assignment, but rather scoped bindings, e.g. OCaml:

However, let is an expression itself.

The advantage of allowing assignment is that we can directly check the return value of a function inside the conditional, e.g. in this Perl snippet:

Perl additionally scopes the declaration to that conditional only, which makes it very useful. It will also warn if you assign inside a conditional without declaring a new variable there – if ($foo = $bar) will warn, if (my $foo = $bar) will not.

Making the assignment in another statement is usually sufficient, but can bring scoping problems:

Golang heavily relies on return values for error checking. It therefore allows a conditional to take an initialization statement:

Other languages use a type system to disallow non-boolean expressions inside a conditional:

Of course that fails when using a function that returns a boolean.

We now have seen different mechanisms to defend against accidental assignment:

  • Disallow assignment as an expression
  • Use static type checking
  • Assignment doesn't exist, we only have let bindings
  • Allow an initialization statement, disallow assignment otherwise
  • Disallow assignment inside a conditional without declaration

I've ranked them in order of ascending preference – assignments inside expressions can be useful (and it's simple to circumvent Python's problems by having an explicit declaration syntax, and a different named argument syntax). But it's ok to disallow them, as there are many other options to the same effect.

Bug-free code is more important than terse code.

amon's user avatar

  • +1 for "Disallow assignment as an expression". The use-cases for assignment-as-an-expression don't justify the potential for bugs and readability issues. –  poke Commented Feb 14, 2014 at 17:00

You said "I figured (with little evidence beyond my personal experience) that the vast majority of times this happened, it was really intended to be comparison operation."

Why not FIX THE PROBLEM?

Instead of = for assignment and == for equality test, why not use := for assignment and = (or even ==) for equality?

If you want to make it harder for the programmer to mistake assignment for equality, then make it harder.

At the same time, if you REALLY wanted to fix the problem, you would remove the C crock that claimed booleans were just integers with predefined symbolic sugar names. Make them a different type altogether. Then, instead of saying

you force the programmer to write:

The fact is that assignment-as-an-operator is a very useful construct. We didn't eliminate razor blades because some people cut themselves. Instead, King Gillette invented the safety razor.

John R. Strohm's user avatar

  • 2 (1) := for assignment and = for equality might fix this problem, but at the cost of alienating every programmer who didn't grow up using a small set of non-mainstream languages. (2) Types other than bools being allows in conditions isn't always due to mixing up bools and integers, it's sufficient to give a true/false interpretation to other types. Newer language that aren't afraid to deviate from C have done so for many types other than integers (e.g. Python considers empty collections false). –  user7043 Commented Feb 13, 2014 at 13:38
  • 1 And regarding razor blades: Those serve a use case that necessitates sharpness. On the other hand, I'm not convinced programming well requires assigning to variables in the middle of an expression evaluation. If there was a simple, low-tech, safe and cost efficient way to make body hair disappear without sharp edges, I'm sure razor blades would have been displaced or at least made much more rare. –  user7043 Commented Feb 13, 2014 at 13:40
  • 1 @delnan: A wise man once said "Make it as simple as possible, but no simpler." If your objective is to eliminate the vast majority of a=b vs. a==b errors, restricting the domain of conditional tests to booleans and eliminating the default type conversion rules for <other>->boolean gets you just about all the way there. At that point, if(a=b){} is only syntactically legal if a and b are both boolean and a is a legal lvalue. –  John R. Strohm Commented Feb 13, 2014 at 15:07
  • Making assignment a statement is at least as simple as -- arguably even simpler than -- the changes you propose, and achieves at least as much -- arguably even more (doesn't even permit if (a = b) for lvalue a, boolean a, b). In a language without static typing, it also gives much better error messages (at parse time vs. run time). In addition, preventing "a=b vs. a==b errors" may not be the only relevant objective. For example, I'd also like to permit code like if items: to mean if len(items) != 0 , and that I'd have to give up to restrict conditions to booleans. –  user7043 Commented Feb 13, 2014 at 15:14
  • 1 @delnan Pascal is a non-mainstream language? Millions of people learned programming using Pascal (and/or Modula, which derives from Pascal). And Delphi is still commonly used in many countries (maybe not so much in yours). –  jwenting Commented Feb 14, 2014 at 9:39

To actually answer the question, yes there are numerous uses of this although they are slightly niche.

For example in Java:

The alternative without using the embedded assignment requires the ob defined outside the scope of the loop and two separate code locations that call x.next().

It's already been mentioned that you can assign multiple variables in one step.

This sort of thing is the most common use, but creative programmers will always come up with more.

Tim B's user avatar

  • Would that while loop condition deallocate and create a new ob object with every loop? –  user3932000 Commented May 3, 2017 at 22:33
  • @user3932000 In that case probably not, usually x.next() is iterating over something. It is certainly possible that it could though. –  Tim B Commented May 4, 2017 at 8:18
  • I can't get the above to compile unless I declare the variable beforehand and remove the declaration from inside. It says Object cannot be resolved to a variable. –  William Jarvis Commented Apr 15, 2021 at 16:42

Since you get to make up all the rules, why now allow assignment to turn a value, and simply not allow assignments inside conditional steps? This gives you the syntactic sugar to make initializations easy, while still preventing a common coding mistake.

In other words, make this legal:

But make this illegal:

Bryan Oakley's user avatar

  • 2 That seems like a rather ad-hoc rule. Making assignment a statement and extending it to allow a = b = c seems more orthogonal, and easier to implement too. These two approach disagree about assignment in expressions ( a + (b = c) ), but you haven't taken sides on those so I assume they don't matter. –  user7043 Commented Feb 13, 2014 at 13:01
  • "easy to implement" shouldn't be much of a consideration. You are defining a user interface -- put the needs of the users first. You simply need to ask yourself whether this behavior helps or hinders the user. –  Bryan Oakley Commented Feb 13, 2014 at 13:05
  • if you disallow implicit conversion to bool then you don't have to worry about assignment in conditions –  ratchet freak Commented Feb 13, 2014 at 13:08
  • Easier to implement was only one of my arguments. What about the rest? From the UI angle, I might add that IMHO incoherent design and ad-hoc exceptions generally hinders the user in grokking and internalising the rules. –  user7043 Commented Feb 13, 2014 at 13:10
  • @ratchetfreak you could still have an issue with assigning actual bools –  jk. Commented Feb 13, 2014 at 13:25

By the sounds of it, you are on the path of creating a fairly strict language.

With that in mind, forcing people to write:

instead of:

might seem an improvement to prevent people from doing:

when they meant to do:

but in the end, this kind of errors are easy to detect and warn about whether or not they are legal code.

However, there are situations where doing:

does not mean that

will be true.

If c is actually a function c() then it could return different results each time it is called. (it might also be computationally expensive too...)

Likewise if c is a pointer to memory mapped hardware, then

are both likely to be different, and also may also have electronic effects on the hardware on each read.

There are plenty of other permutations with hardware where you need to be precise about what memory addresses are read from, written to and under specific timing constraints, where doing multiple assignments on the same line is quick, simple and obvious, without the timing risks that temporary variables introduce

Michael Shaw's user avatar

  • 4 The equivalent to a = b = c isn't a = c; b = c , it's b = c; a = b . This avoids duplication of side effects and also keeps the modification of a and b in the same order. Also, all these hardware-related arguments are kind of stupid: Most languages are not system languages and are neither designed to solve these problems nor are they being used in situations where these problems occur. This goes doubly for a language that attempts to displace JavaScript and/or PHP. –  user7043 Commented Feb 13, 2014 at 13:04
  • delnan, the issue wasn't are these contrived examples, they are. The point still stands that they show the kinds of places where writing a=b=c is common, and in the hardware case, considered good practice, as the OP asked for. I'm sure they will be able to consider their relevance to their expected environment –  Michael Shaw Commented Feb 13, 2014 at 13:51
  • Looking back, my problem with this answer is not primarily that it focuses on system programming use cases (though that would be bad enough, the way it's written), but that it rests on assuming an incorrect rewriting. The examples aren't examples of places where a=b=c is common/useful, they are examples of places where order and number of side effects must be taken care of. That is entirely independent. Rewrite the chained assignment correctly and both variants are equally correct. –  user7043 Commented Feb 13, 2014 at 13:58
  • @delnan: The rvalue is converted to the type of b in one temp, and that is converted to the type of a in another temp. The relative timing of when those values are actually stored is unspecified. From a language-design perspective, I would think it reasonable to require that all lvalues in a multiple-assignment statement have matching type, and possibly to require as well that none of them be volatile. –  supercat Commented Feb 13, 2014 at 19:17

The greatest benefit to my mind of having assignment be an expression is that it allows your grammar to be simpler if one of your goals is that "everything is an expression"--a goal of LISP in particular.

Python does not have this; it has expressions and statements, assignment being a statement. But because Python defines a lambda form as being a single parameterized expression , that means you can't assign variables inside a lambda. This is inconvenient at times, but not a critical issue, and it's about the only downside in my experience to having assignment be a statement in Python.

One way to allow assignment, or rather the effect of assignment, to be an expression without introducing the potential for if(x=1) accidents that C has is to use a LISP-like let construct, such as (let ((x 2) (y 3)) (+ x y)) which might in your language evaluate as 5 . Using let this way need not technically be assignment at all in your language, if you define let as creating a lexical scope. Defined that way, a let construct could be compiled the same way as constructing and calling a nested closure function with arguments.

On the other hand, if you are simply concerned with the if(x=1) case, but want assignment to be an expression as in C, maybe just choosing different tokens will suffice. Assignment: x := 1 or x <- 1 . Comparison: x == 1 . Syntax error: x = 1 .

wberry's user avatar

  • 1 let differs from assignment in more ways than technically introducing a new variable in a new scope. For starters, it has no effect on code outside the let 's body, and therefore requires nesting all code (what should use the variable) further, a significant downside in assignment-heavy code. If one was to go down that route, set! would be the better Lisp analogue - completely unlike comparison, yet not requiring nesting or a new scope. –  user7043 Commented Feb 13, 2014 at 21:36
  • @delnan: I'd like to see a combination declare-and-assign syntax which would prohibit reassignment but would allow redeclaration, subject to the rules that (1) redeclaration would only be legal for declare-and-assign identifiers, and (2) redeclaration would "undeclare" a variable in all enclosing scopes. Thus, the value of any valid identifier would be whatever was assigned in the previous declaration of that name. That would seem a little nicer than having to add scoping blocks for variables that are only used for a few lines, or having to formulate new names for each temp variable. –  supercat Commented Feb 14, 2014 at 3:08

Indeed. This is nothing new, all the safe subsets of the C language have already made this conclusion.

MISRA-C, CERT-C and so on all ban assignment inside conditions, simply because it is dangerous.

There exists no case where code relying on assignment inside conditions cannot be rewritten.

Furthermore, such standards also warns against writing code that relies on the order of evaluation. Multiple assignments on one single row x=y=z; is such a case. If a row with multiple assignments contains side effects (calling functions, accessing volatile variables etc), you cannot know which side effect that will occur first.

There are no sequence points between the evaluation of the operands. So we cannot know whether the subexpression y gets evaluated before or after z : it is unspecified behavior in C. Thus such code is potentially unreliable, non-portable and non-conformant to the mentioned safe subsets of C.

The solution would have been to replace the code with y=z; x=y; . This adds a sequence point and guarantees the order of evaluation.

So based on all the problems this caused in C, any modern language would do well to both ban assignment inside conditions, as well as multiple assignments on one single row.

Not the answer you're looking for? Browse other questions tagged language-agnostic syntax operators or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • Would it be out of style to start a history book with a poem I wrote?
  • Where did they get facehuggers from?
  • Are fuel efficiency charts available for mainstream engines?
  • What is the least number of colours Peter could use to color the 3x3 square?
  • Visual assessment of scatterplots acceptable?
  • What are the most common types of FOD (Foreign Object Debris)?
  • Multiplicity of the smallest non-zero Laplacian eigenvalue for tree graphs
  • Why does the guardian who admits guilt pay more than when his guilt is established by witnesses?
  • Circuit that turns two LEDs off/on depending on switch
  • Looking for the name of a possibly fictional science fiction TV show
  • Beatles reference in parody story from the 1980s
  • Is this host and 'parasite' interaction feasible?
  • How to simplify input to a table with many columns?
  • Weird error in RegionPlot3D?
  • On the convex cone of convex functions
  • What is the missing fifth of the missing fifths?
  • I want to be a observational astronomer, but have no idea where to start
  • How would you read this time change with the given note equivalence?
  • Flats on gravel with GP5000 - what am I doing wrong?
  • How does a miner create multiple outputs in a coinbase transaction?
  • Why do "modern" languages not provide argv and exit code in main?
  • Is reading sheet music difficult?
  • Starting with 2014 "+" signs and 2015 "−" signs, you delete signs until one remains. What’s left?
  • Question about word (relationship between language and thought)

the assignment to variable name has no effect

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

Variable not changing after assigning another value to its dependent variable

Entering the following code into Python 3.5 shell gives me an answer I didn't expect, very basic I know but would somebody help me with an explanation please.

These were all on separate lines each preceded by >>>

I expected 6, but the "new" x has not been used.

Georgy's user avatar

  • Possible duplicate of Python assigning multiple variables to same value? list behavior –  vaultah Commented Sep 23, 2017 at 1:00
  • Or python variables are pointers . Or Why variable = object doesn't work like variable = number . –  vaultah Commented Sep 23, 2017 at 1:08
  • Does this answer your question? Are python variables pointers? or else what are they? –  Georgy Commented May 27, 2020 at 13:01

4 Answers 4

The 'a' variable will only be updated if you update it deliberately. In order to update 'a' after you have changed 'x', you will need to execute the line a = x*y again.

If you copy and paste your code into here http://www.pythontutor.com/visualize.html#mode=edit it will give you a good visualization of what is going on!

Charley Carriero's user avatar

a = x*y isn't an equation that automatically updates a whenever you change x or y . It sets a to x*y once when the statement is run. Any changes to x or y afterward have no effect on a .

You'll need to manually update a when you change x or y , or, if the situation allows it, use local functions to do what @Silvio's answer shows. It's handy to create local shortcuts to help clean up code.

Carcigenicate's user avatar

When you assign a , the value is set then and there.

The current values of x and y are used. The expression x * y isn't stored anywhere, so Python can't possibly know to update it. If you want a value that automatically updates based on the values of its variables, you can use a closure.

This ensures that the expression is evaluated every time a is called.

Silvio Mayolo's user avatar

a variable won't be updated. You may want to create a function this way

And then you can create the tuple

  • So where's the explanation the OP asked for? –  vaultah Commented Sep 23, 2017 at 1:11

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 python variables or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • 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

  • On the convex cone of convex functions
  • Preventing BEAST by using authorisation header instead of cookies
  • Does Psalm 127:2 promote laidback attitude towards hard work?
  • Setting the desired kernel in GRUB menu
  • Is this host and 'parasite' interaction feasible?
  • The head of a screw is missing on one side of the spigot outdoor
  • How cheap would rocket fuel have to be to make Mars colonization feasible (according to Musk)?
  • Advanced Composite Solar Sail (ACS3) Orbit
  • Are fuel efficiency charts available for mainstream engines?
  • Somebody used recommendation by an in-law – should I report it?
  • Flats on gravel with GP5000 - what am I doing wrong?
  • What is the resulting initiative order when a readied action triggers after a summoned monsters action but before the summoner?
  • How can I make this equation look better?
  • \documentclass in separate .tex file
  • I want to be a observational astronomer, but have no idea where to start
  • Multi Level Access
  • Replacement derailleur for Schwinn
  • Fundamental Question on Noise Figure
  • Would it be out of style to start a history book with a poem I wrote?
  • Why do "modern" languages not provide argv and exit code in main?
  • Why does each leg of my 240V outlet measure 125V to ground, but 217V across the hot wires?
  • What happens on a CAN bus when impedance is too low?
  • Understanding the parabolic state of a quantum particle in the infinite square well
  • Looking for the name of a possibly fictional science fiction TV show

the assignment to variable name has no effect

COMMENTS

  1. The assignment to variable [Something] has no effect

    The code you have is perfectly valid. In effect, you created a constructor that does not assign any variable : public Module(String name,int bind,Category category) { } and below you created an initializer code block that is called by every constructor : { this.name = name; this.bind = bind; this.category = category; }

  2. The assignment to a variable name has no effect

    1. return (fullName = fullName=firstName + " " + lastName); You should to separate this code. First you assign new value for full name (with only 1 assign operator =), then return full name. Another way is just say: return firstName + " " + lastName; PS: Yes you're right, assign expression will run first, then it return the new value of full name.

  3. java

    14. count++ and ++count are both short for count=count+1. The assignment is built in, so there's no point to assigning it again. The difference between count++ (also knows as postfix) and ++count (also known as prefix) is that ++count will happen before the rest of the line, and count++ will happen after the rest of the line.

  4. The assignment to variable x has no effect

    The assignment to variable x has no effect. On the otherhand if i use x= (x=x+1) then i get output as 11 without any warning. I think i am doing something wrong, but just cant figure out. public class A { int x; public static void main (String args []) { A a = new A (); a.someMethod (); } someMethod () { x=x++; System.out.println ("Value of x ...

  5. Useless assignment to local variable

    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. Example¶ The following example shows six different types of assignments to local variables whose value is not read:

  6. Java中有关this的一个问题_the assignment to variable has no effect-CSDN博客

    我们注意到系统给出了一个警告:"The assignment to variable i has no effect." 这个警告说明了构造器中的"i=i"是个毫无意义的语句。. 经过debug发现,在对象ct创建时,构造器中的语句没有起到任何作用,对于i的赋值直接采用的是默认值1. 如果传入参数的名称和域变量 ...

  7. Fix warnings: The assignment to variable has no effect

    JDK; JDK-8289381; Fix warnings: The assignment to variable has no effect

  8. Variable Assignment Having No Effect

    So the rule is local variable x shadows the static variable x. You should do x = Test_Assignment.x; if you want to assign the value of static x to local x. If you like our products and services, please help us by posting your review here .

  9. Setting the variable $USERNAME has no effect

    login(1) is the process who set these variables. both USER and LOGNAME variables can be modified and later access return the new value. find nowhere the reference for USERNAME, and this variable is not set in bash4.3. bash defines a UID readonly numerical variable. attempt to change this variable in bash fails.

  10. buffer: remove unnecessary assignment in fromString #50199

    The assignment to the encoding variable has no effect. Refs: nodejs#29217 PR-URL: nodejs#50199 Reviewed-By: Yagiz Nizipli <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> targos pushed a commit that referenced this pull request Nov 11, 2023

  11. repl: Failed assignment "blocks" further assignments to a variable name

    Try to assign to the same variable name using let|const|var OR try to use the variable; Result: The variable name is no longer available, because you get a TypeError: Identifier has already been declared OR ReferenceError: variable is not defined if you try to use the variable name. Expected Behavior: The variable name to remain undeclared.

  12. Python Variable Naming: Rules, Conventions, and Best Practices

    Best Practices and Tips. Descriptive Names: Choose meaningful names that convey the purpose of the variable.Bad: a, var1, x Good: student_age, total_items, file_path. Length of Names: Keep the variable name concise yet descriptive.Example: num (short for number), not n or number_of_items. Avoid Ambiguity: Use clear and unambiguous terms.Example ...

  13. MSC12-C. Detect and remove code that has no effect or is never executed

    Exceptions. MSC12-EX1: In some situations, seemingly dead code may make software resilient. An example is the default label in a switch statement whose controlling expression has an enumerated type and that specifies labels for all enumerations of the type. (See MSC01-C. Strive for logical completeness.)Because valid values of an enumerated type include all those of its underlying integer type ...

  14. Assignment (=)

    So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String; you can just type the unqualified String.To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name ...

  15. How to resolve -W0104: Statement seems to have no effect (pointless

    Unused variables: If you declare a variable but never use it, the statement assigning a value to that variable becomes pointless. For example: int x = 5; // Warning: Statement seems to have no effect. Unused return values: If you call a function that returns a value but do not use that value, the statement becomes pointless. For example:

  16. eclipse警告"assignment to variable xxx has no effect"についての覚書き

    eclipseバージョンは2022-6(4.24.0)です。下記キャプチャのように、"assignment to variable a has no effect"の警告が、意味のないはずの文B(a=a++;)ではなく、E(a=++a;)の文の方に出てきたからです。 先に言っておくと、これは正しい仕様です。

  17. GN assignment has no effect / variable unused before it went out of

    GN assignment has no effect / variable unused before it went out of scope . 2 Hotlists Mark as Duplicate . Comments (6) Dependencies . Duplicates (0) Blocking (0) Resources (0) ... Assignment had no effect. compiler_prefix = "" ^-You set the variable "compiler_prefix" here and it was unused before it went out of scope. See //BUILD.gn:65:1 ...

  18. Python

    Python - Variable Names

  19. java

    Because when you declare a parameter in. void stud(int id,String name) you are hiding (shadowing) the instance variable id.Therefore, whenever id is accessed within the method stud, it will refer to the local id, not the instance variable.. If you want to access to the instance variable, use the this keyword:. void stud(int id,String name) { this.id = id; // ...

  20. language agnostic

    For starters, it has no effect on code outside the let's body, and therefore requires nesting all code (what should use the variable) further, a significant downside in assignment-heavy code. If one was to go down that route, set! would be the better Lisp analogue - completely unlike comparison, yet not requiring nesting or a new scope.

  21. python

    When you assign a, the value is set then and there. a = x * y The current values of x and y are used. The expression x * y isn't stored anywhere, so Python can't possibly know to update it. If you want a value that automatically updates based on the values of its variables, you can use a closure.