Understanding the 'Warning: Suggest Parentheses Around Assignment Used as Truth Value [-wparentheses]' - Improve Your Code Today

David Henegar

In this guide, we will help you understand the -Wparentheses warning in C and C++ programming, which suggests adding parentheses around an assignment used as a truth value. This warning is generated by the compiler when it detects potential issues with operator precedence or when the code might be confusing for others to read.

We will break down the causes of this warning, show you how to fix it, and provide a step-by-step solution for your code. Additionally, we will cover some frequently asked questions related to this warning.

Table of Contents

What causes the warning, how to fix the warning, step-by-step solution, related links.

The -Wparentheses warning is triggered when the compiler detects an assignment used as a truth value in a conditional expression without proper parentheses. This warning is intended to help you avoid common pitfalls associated with operator precedence and improve the readability of your code.

For example, consider the following code snippet:

In this case, the compiler will issue a warning because the assignment operator = has lower precedence than the comparison operators. This means that the code might not behave as intended, and the conditional expression can be confusing for others to read.

To fix the warning, you can:

  • Add explicit parentheses around the assignment used as a truth value, or
  • Use the appropriate comparison operator (like == , != , < , > , <= , or >= ) instead of the assignment operator.

Here's an example of how to fix the warning using the first method:

And here's an example using the second method:

Follow these steps to fix the -Wparentheses warning in your code:

  • Identify the line of code that causes the warning.
  • Determine if the assignment used as a truth value is intentional or a mistake.
  • If intentional, add parentheses around the assignment to make the intention clear and suppress the warning.
  • If it's a mistake, replace the assignment operator with the appropriate comparison operator to fix the logic.

What is the purpose of the -Wparentheses warning?

The -Wparentheses warning is intended to help you avoid common pitfalls associated with operator precedence and improve the readability of your code. It suggests adding parentheses around an assignment used as a truth value in a conditional expression.

Can I suppress the -Wparentheses warning?

Yes, you can suppress the -Wparentheses warning by adding -Wno-parentheses to your compiler flags. However, it is generally not recommended, as the warning helps identify potential issues in your code.

What is operator precedence in C and C++?

Operator precedence determines the order in which operators are evaluated in an expression. In C and C++, different operators have different precedence levels, with some operators having higher precedence than others.

Are there other similar warnings to -Wparentheses ?

Yes, there are other similar warnings in C and C++, such as -Wsequence-point , -Wuninitialized , and -Wmaybe-uninitialized , which help you identify potential issues related to operator precedence, uninitialized variables, and other common pitfalls.

Can the -Wparentheses warning catch all issues related to operator precedence?

No, the -Wparentheses warning helps identify potential issues with assignment operators used as truth values in conditional expressions, but it might not catch all issues related to operator precedence. It is essential to understand the precedence rules and write clear, readable code.

  • GCC Warning Options
  • Understanding Operator Precedence 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.

C

C Programming

Tiny C Projects

C Brain Teasers

XML and JSON

Online Training

Solution for Exercise 8-7

* A variable assignment in C is always a TRUE condition. So Line 10 evaluates TRUE no matter what value is assigned to variable a .

* Modify Line 9 so that it reads:

Build and run. The output reads 5 equals -3 because the assignment is TRUE, not because the value of variable a is -3.

* The point of the exercise isn't to describe how assignments are always TRUE, but rather that you need to use two equal signs instead of one when making an "is equal to" comparison.

* The compiler may warn of the assignment a=-3 (or a=5 ) in the comparison. The warning message I see is "suggest parentheses around assignment used as truth value," which is probably just telling you to use two equal signs instead of one, I suppose.

* An exception to the assignment = always being TRUE is when you assign a zero value, as in:

Because the value zero is assigned, the result is FALSE. Watch out for that one.

Exercise ex0808 →

Copyright © 1997-2024 by QPBC. All rights reserved

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 world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...

Hot Network Questions

  • Very simple CSV-parser in Java
  • Arduino Uno Serial.write() how many bits are actually transmitted at once by UART and effect of baudrate on other interrupts
  • ASCII 2D landscape
  • How to change my document's font
  • Are these colored sets closed under multiplication?
  • How can we speed up the process of returning our lost luggage?
  • Solaris 11 cbe: no more updates?
  • How would you address the premises of Schellenberg's non-resistant divine hiddenness argument?
  • Why does fdisk create a 512B partition when I enter +256K?
  • Is it really a "space walk" (EVA proper) if you don't get your feet wet (in space)?
  • Function with memories of its past life
  • What was the newest chess piece
  • Explicit Examples for Unrestricted Hartree Fock Calculations
  • What does "иного толка" mean? Is it an obsolete meaning?
  • Python script to renumber slide ids inside a pptx presentation
  • Do carbon fiber wings need a wing spar?
  • Can socks5 proxies work similiar to http connect?
  • View undo history of Windows Explorer on Win11
  • How should I email HR after an unpleasant / annoying interview?
  • Can All Truths Be Scientifically Verified?
  • I have been trying to solve this Gaussian integral, which comes up during the perturbation theory
  • Rich Mental Images
  • Why is the center of a meniscus completely flat?
  • Place with signs in Chinese & Arabic

c assignment truth value

Next: Execution Control Expressions , Previous: Arithmetic , Up: Top   [ Contents ][ Index ]

7 Assignment Expressions

As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues ) because they are locations that hold a value.

An assignment in C is an expression because it has a value; we call it an assignment expression . A simple assignment looks like

We say it assigns the value of the expression value-to-store to the location lvalue , or that it stores value-to-store there. You can think of the “l” in “lvalue” as standing for “left,” since that’s what you put on the left side of the assignment operator.

However, that’s not the only way to use an lvalue, and not all lvalues can be assigned to. To use the lvalue in the left side of an assignment, it has to be modifiable . In C, that means it was not declared with the type qualifier const (see const ).

The value of the assignment expression is that of lvalue after the new value is stored in it. This means you can use an assignment inside other expressions. Assignment operators are right-associative so that

is equivalent to

This is the only useful way for them to associate; the other way,

would be invalid since an assignment expression such as x = y is not valid as an lvalue.

Warning: Write parentheses around an assignment if you nest it inside another expression, unless that is a conditional expression, or comma-separated series, or another assignment.

  The basics of storing a value.
  Expressions into which a value can be stored.
  Shorthand for changing an lvalue’s contents.
  Shorthand for incrementing and decrementing an lvalue’s contents.
  Accessing then incrementing or decrementing.
  How to avoid ambiguity.
  Write assignments as separate statements.

Coding Forums

  • Search forums
  • C Programming

Confused - suggest parentheses around assignment used as truth value

  • Thread starter Richard Tobin
  • Start date Apr 17, 2007

Richard Tobin

  • Apr 17, 2007
if (loc == 'u') <- warning: suggest parentheses around assignment used as truth value Click to expand...
From some responses, it was suggested to add ( ) around the comparion, Click to expand...

Eric Sosman

Hi all, I'm new to C and kind of confused on this. I've had a look around this group for suggestions but still not sure why the warning is occurring. What I've done is this <code snip> Click to expand...
Hi all, I'm new to C and kind of confused on this. I've had a look around this group for suggestions but still not sure why the warning is occurring. What I've done is this <code snip> void foo(char loc) { ... if (loc == 'u') <- warning: suggest parentheses around assignment used as truth value { for (i=0, i<=max; i++) foo2( .... ); } } which I tried. void foo(char loc) { ... if ((loc == 'u')) <- still get warning: suggest parentheses around assignment used as truth value { for (i=0, i<=max; i++) foo2( .... ); } } Even after placing in the 2nd ( ) around my comparison, gcc -Wall is still giving me the waring. Can anyone shed some light on this please ? TIA Nat Click to expand...
  • Apr 18, 2007
I'd suggest checking a) That you really do have "if (loc == 'u')" and absolutely definitely do not have "if (loc = 'u')"; b) That "loc" is not a #define or the like. What happens if you change the variable name to something else? c) That the line you are carefully examining is indeed the same line that the compiler is complaining about - sometimes line numbering goes a bit odd. What happens if you comment it out? Hope these help you track down the problem... Paul.- Hide quoted text - - Show quoted text - Click to expand...

Francine.Neary

  • Apr 22, 2007
It was the last comment that helped me out the most. gcc -Wall was stating that my comparsion was somehow wrong so my focus was on the if (loc == 'u') problem, as it corresponded to the line number that gcc gave. I had double checked that I used == and not = when in fact it was my for loop that was giving me problems. Click to expand...
I personally find this warning incredibly pointless and irritating. I use assignments as truth values extremely frequently, and I don't need the compiler to patronize me! Click to expand...

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Similar Threads

6
14
3
0
20
2
4
3

Members online

Forum statistics, latest threads.

  • Started by alora001
  • Today at 7:55 AM
  • Started by civilgrom
  • Saturday at 8:46 PM
  • Started by spero
  • Friday at 5:45 PM
  • Started by JonnyD
  • Thursday at 5:12 PM
  • Started by Ashley
  • Wednesday at 10:53 AM
  • Started by benparker431
  • Tuesday at 7:58 PM
  • Started by IBMJunkman
  • Sep 9, 2024
  • Started by jimandy
  • Sep 8, 2024
  • Started by najasnake12
  • Started by A.N.Omalum

C Operator Introduction

C assignment =, c compound assignment, c addition +, c subtraction -, c multiplication *, c division /, c operator precedence, c sizeof operator, c modulus %, c increment decrement ++ --, c relational operators, c truth value, c relational operators precedence, c logical operators, c logic and &&, c logic or ||, c logic not , c logic check letter case, c logical count char word line, c expression value, c expressions and statements, c type conversions, c cast operator, c conditional operator :, c conditional operator demo, c conditional operator demo 2, c review question 1, c review question 2, c exercises 1, c exponential growth, c fahrenheit to celsius.

For C, a true expression has the value 1, and a false expression has the value 0.

More generally, all nonzero values are regarded as true, and only 0 is recognized as false.

An expression in C always has a value. This is true even for relational expressions.

That example prints the values of two relational expressions-one true and one false.

The code above assigns the values of two relational expressions to two variables.

It assigns true_val the value of a true expression, and false_val the value of a false expression.

Running the program produces the following simple output:

Some C programs use the following construction for loops that are meant to run forever because 1 always is true:

What Else Is True?

What values are true?

Here are the results:

The first loop executes when n is 3, 2, and 1, but terminates when n is 0.

Similarly, the second loop executes when n is -3, -2, and -1, but terminates when n is 0.

Logo

  • Search in titles only Search in C only Search
  • Advanced Search

suggest parentheses around assignment used as truth value

  • Latest Activity
  • Time All Time Today Last Week Last Month
  • Show All Discussions only Photos only Videos only Links only Polls only Events only
  • Join Date: Mar 2013
  • Join Date: Mar 2007
  • Posts: 9214

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.

Understanding the concept of “truth assignment”.

Working on the book: Derek Goldrei. " Propositional and Predicate Calculus " (p. 40)

The author briefly introduces the concept of a function v :

We talked informally about knowing whether, in a particular set of circumstances, each propositional variable is true or false. More formally and elegantly, thsi set of circumstances is a function $v \colon P \to \{T,F\}$ , where $P$ is the set of propositional variables in our language.

Before introducing the concept of truth assignment , explains:

Let $Form(P, S)$ be the set of all formulas built up from propositional variables in a set $P$ using connectives in a set $S$ which includes $\land$ . We shall say that a function $v \colon Form(P,S) \to \{T,F\}$ respects the truth table $\land$ if $$ v((\theta \land \psi))= \begin{cases} T, &\text{if } v(\theta))=v(\psi)=T\\ F, &otherwise, \\ \end{cases} $$ for all formulas $\theta, \psi \in Form(P,S)$ .

I see how function $v$ respects the truth table of $\land$ . My question is:

  • In which way are the truth value of $v(\theta)$ and $v(\psi)$ determined in that piecewise function ?
  • What is the criteria for deciding whether $v(\theta)$ (or any propositional variable) is going to be $T$ or $F$ ?
  • propositional-calculus

F. Zer's user avatar

  • $\begingroup$ See van Dalen , page 17 for the definition and the basic result: "If a valuation is only given for atoms then it is, by virtue of the definition by recursion [see your previous post], possible to extend it to all propositions. " $\endgroup$ –  Mauro ALLEGRANZA Commented Oct 8, 2020 at 6:40
  • $\begingroup$ Thank you so much, @Mauro ALLEGRANZA. That's exactly what I do not understand. Could you explain a little bit ? What does "...possible to extend it to all propositions", mean ? I see how the value of compound formulas is computes; I just do not see it when it comes to atoms. I mean, what determines the assignment of T or F to an atomic formula. $\endgroup$ –  F. Zer Commented Oct 8, 2020 at 12:05
  • $\begingroup$ Thank for the offering. I will appreciate if you could clarify the meaning of "...possible to extend it to all propositions". Also, is perhaps the assignment to atoms random ? I feel this is not really complicated but a detail evades me. $\endgroup$ –  F. Zer Commented Oct 8, 2020 at 12:32

3 Answers 3

Ultimately the truth value $v(\varphi)$ of any formula $\varphi$ is determined by the truth values that $v$ assigns to the propositional variable appearing in $\varphi$ . Consider, for instance the following formula $\varphi$ :

$$(p\land\neg q)\lor(r\land q)\to p$$

If $v(p)=F$ , $v(q)=T$ , and $v(r)=F$ , then:

  • $v(\neg q)$ must be $F$ in order to respect to truth table for $\neg$ ;
  • $v(p\land\neg q)$ must then also be $F$ in order to respect the truth table for $\land$ ;
  • $v(r\land q)$ must be $F$ for the same reason;
  • $v\big((p\land\neg q)\lor(r\land q)\big)$ must be $F$ in order to respect the truth table for $\lor$ ; and finally
  • $v(\varphi)$ must be $T$ in order to respect the truth table for $\to$ .

If we change the truth value of $r$ by setting $v(r)=T$ , we must then have $v(r\land q)=T$ , $v\big((p\land\neg q)\lor(r\land q)\big)=T$ , and $v(\varphi)=F$ .

In practice truth assignments are very often presented in the form of tables showing the truth values assigned to a particular formula under all possible assignments of truth values to its propositional variables. In this case we’d have the following table, and we could read off that $v(\varphi)=T$ for all truth assignments to $p,q$ , and $r$ except the one mentioned immediately above, the one in the fifth line of the table:

$$\begin{array}{c|c|c} p&q&r&p\land\neg q&r\land q&(p\land\neg q)\lor(r\land q)&\varphi\\\hline T&T&T&F&T&T&T\\ T&T&F&F&F&F&T\\ T&F&T&T&F&T&T\\ T&F&F&T&F&T&T\\ F&T&T&F&T&T&F\\ F&T&F&F&F&F&T\\ F&F&T&F&F&F&T\\ F&F&F&F&F&F&T \end{array}$$

Brian M. Scott's user avatar

  • $\begingroup$ Very clear. Thank you so much, @Brian M. Scott ! I see what you explain about respecting the truth table of logical connectives. But, in which way the value of $v(\theta)$ is determined ($\theta$ being an atomic proposition) ? $\endgroup$ –  F. Zer Commented Oct 8, 2020 at 11:59
  • $\begingroup$ Taking a simple example, I know the value of $\sqrt{4}$ is going to be $2$, but in terms of truth assignments, I cannot see a predictable way of determining if a certain proposition is going to be true or false. $\endgroup$ –  F. Zer Commented Oct 8, 2020 at 11:59
  • $\begingroup$ Perhaps, there is a subtle point about functions that I'm not getting... $\endgroup$ –  F. Zer Commented Oct 8, 2020 at 12:00
  • $\begingroup$ @F.Zer: I’m not quite sure what you’re asking. Are you asking how, if $p$ is a propositional variable, one determines the truth value of $p$? That’s not a question with which propositional logic deals: propositional logic deals with how truth values of propositions are correctly combined. $\endgroup$ –  Brian M. Scott Commented Oct 8, 2020 at 16:27
  • 1 $\begingroup$ @F.Zer: Yes, that’s correct. For instance, the truth table in my answer shows every one of the $8$ possible truth assignments to the three variable $p,q$, and $r$, one per line. $\endgroup$ –  Brian M. Scott Commented Oct 8, 2020 at 17:05

The above answers are thorough, but they overcomplicate matters by quite a bit by being too formal. A truth assignment ν is simply a row of values of atomic propositions in a truth table , nothing more, nothing less.

This row of atomic proposition values can be thought of as a function ν(φ) → {T, F} , which is true or T , if the value of the formula φ is true with that combination of values of atomic propositions ν and false or F, if the fomula φ is not true with said values. For example, if it is raining and cloudy or raining = T and cloudy = T , then

and the sequence raining cloudy = T T = ν for which ν(φ) = ν(raining ∧ cloudy) = T .

Another way of writing the fact that ν(φ) = T , or that φ is true with the observed combination of values of the atomic propositions, is ν ⊧ φ , or ν is a model of the formula  φ . If φ is not true with the given combination of atomic proposition values ν , we say that ν ̸⊧ φ , or that ν is a counter model of φ .

Anyways, thinking about this in terms of truth tables is in my opinion more illustrative than most alternative presentations.

sesodesa's user avatar

See Dirk van Dalen, Logic and Structure (5th ed., 2013) , page 17 for the definition and the basic result:

"If a valuation is only given for atoms then it is, by virtue of the definition by recursion, possible to extend it to all propositions."

What is a valuation ? Simply a function: $v : \text {PROP} \to \{ 0,1 \}$ ,

where [see page 7 ] $\text {PROP} = \{ p_0, p_1, \ldots \}$ is the collection of proposition symbols .

Side condition : van Dalen uses $\bot$ and consider it as a $0$ -ary connective. Thus, he needs the clause: for every valuation $v$ we must have: $v(\bot)=0$ .

Silly examples of valuations:

$v(p_i)=0$ , for every $i$ ; $v'(p_i)=1$ , for every $i$ .

Starting with an assignment $v$ , we can easily show how the truth tables for the basic connectives [see page 18 ] give us the recipe for computing the truth value for a formula $\varphi$ whatever.

Consider the formula $((p_0 ∧ p_1) → (\lnot p_0))$ [similar to the example used in your previous post ] and build the usual truth table:

$$\begin{array}{c|c|c} p_0&p_1&(p_0 \land p_1)&(\lnot p_0)&((p_0\land p_1)\to(\lnot p_0))&\\\hline 1&1&1&0&0\\ 1&0&0&0&1\\ 0&1&0&1&1\\ 0&0&0&1&1\\ \end{array}$$

Consider now the following valuation: $v(p_0)=0$ and $v(p_1)=1$ . It simply amounts to the third line in the table above.

Note : as we can imagine [but we can prove it: see Lemma 2.2.3 , page 18], what matters are only the value that the valuation assigns to the propositional symbols occurring into the formula.

The "recipe" is:

(i) $v(p_0)=0$ ; thus $v[(\lnot p_0)]=1$ .
(ii) $v(p_0)=0$ and $v(p_1)=1$ ; thus $v[(p_0 \land p_1)]=0$ .
(iii) $v[(p_0 \land p_1)]=0$ and $v[(\lnot p_0)]=1$ ; thus $v[((p_0 \land p_1)\to (\lnot p_0))]=1$ .

Note : in computing the truth value of the formula, we have followed the formation sequence [see Definition 2.1.4 , page 9] of the formula:

$p_0, p_1, (p_0 \land p_1), (\lnot p_0), ((p_0 \land p_1)\to (\lnot p_0))$ .

Mauro ALLEGRANZA's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged logic propositional-calculus ..

  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • 2024 Election Results: Congratulations to our new moderator!

Hot Network Questions

  • Using a standard junction box as a pull point in a run. Do I need to leave a loop of wire in the box or should I take the slack out?
  • Is it true that before European modernity, there were no "nations"?
  • XeLaTeX does not show latin extended characters with stix2
  • Can't find AVI Raw output on Blender (not on video editing)
  • Will a recent B2 travel to the same location as my F1 college application affect the decision
  • Offline autocue (teleprompter) program for Windows?
  • How was Adam given the 7 Noahide laws without animals or women in existence?
  • Seeking a Text-Based Version of Paul Dirac's 1926 Paper on Quantum Mechanics
  • Do black holes convert 100% of their mass into energy via Hawking radiation?
  • I have been trying to solve this Gaussian integral, which comes up during the perturbation theory
  • Why does a capacitor act as an open circuit under a DC circuit?
  • What was the newest chess piece
  • Inverses of Morphisms Necessarily Being Morphisms
  • Is Sagittarius A* smaller than we might expect given the mass of the Milky Way?
  • Can the concept of a perfectly good God creating beings vulnerable to sin be philosophically justified?
  • Explode multiple columns with different lengths
  • How can we speed up the process of returning our lost luggage?
  • When a creature enchanted with Fungal Fortitude dies and returns to the battlefield, does it keep Fungal Fortitude?
  • Is it really a "space walk" (EVA proper) if you don't get your feet wet (in space)?
  • What does "иного толка" mean? Is it an obsolete meaning?
  • Are these colored sets closed under multiplication?
  • What makes amplifiers so expensive?
  • Explicit Examples for Unrestricted Hartree Fock Calculations
  • Which cartoon episode has Green Lantern hitting Superman with a tennis racket and sending him flying?

c assignment truth value

  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Need help with warning message

  Need help with warning message

c assignment truth value

clear(); menu(); selector( select); hideCursor(); main() { hideCursor(); menu(); 0; } hideCursor() { HANDLE consoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO info; info.dwSize = 100; info.bVisible = FALSE; SetConsoleCursorInfo(consoleHandle, &info); } menu() { select = 0; x; selector(select); (x = getch()) { (x == 72) { select -= 2; (select < 0) select = 0; selector(select); } (x == 80) { select += 2; (select > SELECT_END) select = SELECT_END; selector(select); } } } clear() { system( ); } selector( select) { *selections[] = { , , , , , , , , , , , , , , }; i; clear(); (i = 0; i < ARRAYSIZE(selections); i += 2) { (i == select) printf ( , selections[i]); printf ( , selections[i + 1]); } }
(x = getch())
Ohh.. so if the code is Okay and I was thinking the same thing, if I put the "==" it gives me another warning at the next line that should be this if(x == 72), and if I change it to this if(x = 72) it says comparison between pointer and integer.
in which scenario does x = getch() become false?
suggest parentheses around assignment used as truth value
==
comparison between pointer and integer
(1) { x = getch(); }
((x = getch()))
And I got no warnings.
To remove it, enclose the assignment in a second pair of parentheses.
For Windows it should be _getch(). To terminate, Alt-Gr then a character.
menu() { select = 0; x; selector(select); ((x = getch())) { (x == 72) { select -= 2; (select < 0) select = SELECT_END - 1; selector(select); } (x == 80) { select += 2; (select > SELECT_END) select = 0; selector(select); } (x == 13) { (select <= 1) { inputData(); } (select <= 2) { retrieveData(); } (select <= 4) { modifyData(); } (select <= 6) { viewInfo(); } (select <= 8) { deleteData(); } (select <= 10) { about(); } (select <= 12) { printf( ); Sleep(1000); system( ); exit(0); } } } }
x=NULL; (x=somefunc())
Propositional Logic

2.1 Introduction

Propositional Logic is concerned with propositions and their interrelationships. The notion of a proposition here cannot be defined precisely. Roughly speaking, a proposition is a possible condition of the world that is either true or false, e.g. the possibility that it is raining, the possibility that it is cloudy, and so forth. The condition need not be true in order for it to be a proposition. In fact, we might want to say that it is false or that it is true if some other proposition is true.

In this chapter, we first look at the syntactic rules that define the language of Propositional Logic. We then introduce the notion of a truth assignment and use it to define the meaning of Propositional Logic sentences. After that, we present a mechanical method for evaluating sentences for a given truth assignment, and we present a mechanical method for finding truth assignments that satisfy sentences. We conclude with some examples of Propositional Logic in formalizing Natural Language and Digital Circuits.

In Propositional Logic, there are two types of sentences -- simple sentences and compound sentences. Simple sentences express simple facts about the world. Compound sentences express logical relationships between the simpler sentences of which they are composed.

Simple sentences in Propositional Logic are often called proposition constants or, sometimes, logical constants . In what follows, we write proposition constants as strings of letters, digits, and underscores ("_"), where the first character is a lower case letter. For example, raining is a proposition constant, as are rAiNiNg , r32aining , and raining_or_snowing . Raining is not a proposition constant because it begins with an upper case character. 324567 fails because it begins with a number. raining-or-snowing fails because it contains hyphens (instead of underscores).

Compound sentences are formed from simpler sentences and express relationships among the constituent sentences. There are five types of compound sentences, viz. negations, conjunctions, disjunctions, implications, and biconditionals.

A negation consists of the negation operator ¬ and an arbitrary sentence, called the target . For example, given the sentence p , we can form the negation of p as shown below.

A conjunction is a sequence of sentences separated by occurrences of the ∧ operator and enclosed in parentheses, as shown below. The constituent sentences are called conjuncts . For example, we can form the conjunction of p and q as follows.

( p ∧ q )

A disjunction is a sequence of sentences separated by occurrences of the ∨ operator and enclosed in parentheses. The constituent sentences are called disjuncts . For example, we can form the disjunction of p and q as follows.

( p ∨ q )

An implication consists of a pair of sentences separated by the ⇒ operator and enclosed in parentheses. The sentence to the left of the operator is called the antecedent , and the sentence to the right is called the consequent . The implication of p and q is shown below.

( p ⇒ q )

A biconditional is a combination of an implication and a reverse implication. For example, we can express the biconditional of p and q as shown below.

( p ⇔ q )

Note that the constituent sentences within any compound sentence can be either simple sentences or compound sentences or a mixture of the two. For example, the following is a legal compound sentence.

(( p ∨ q ) ⇒ r )

One disadvantage of our notation, as written, is that the parentheses tend to build up and need to be matched correctly. It would be nice if we could dispense with parentheses, e.g. simplifying the preceding sentence to the one shown below.

p ∨ q ⇒ r

Unfortunately, we cannot do without parentheses entirely, since then we would be unable to render certain sentences unambiguously. For example, the sentence shown above could have resulted from dropping parentheses from either of the following sentences.

( p ∨ ( q ⇒ r ))

The solution to this problem is the use of operator precedence . The following table gives a hierarchy of precedences for our operators. The ¬ operator has higher precedence than ∧; ∧ has higher precedence than ∨; ∨ has higher precedence than ⇒; and ⇒ has higher precedence than ⇔.

In sentences without parentheses, it is often the case that an expression is flanked by operators, one on either side. In interpreting such sentences, the question is whether the expression associates with the operator on its left or the one on its right. We can use precedence to make this determination. In particular, we agree that an operand in such a situation always associates with the operator of higher precedence. The following examples show how these rules work in various cases. The expressions on the right are the fully parenthesized versions of the expressions on the left.

¬ ∧ ((¬ ) ∧ )
∧ ¬ ( ∧ (¬ ))
∧ ∨ (( ∧ ) ∨ )
∨ ∧ ( ∨ ( ∧ ))
⇒ ⇔ (( ⇒ ) ⇔ ))
⇔ ⇒ ( ⇔ ( ⇒ ))

When an operand is surrounded by two ∧ operators or by two ∨ operators, the operand associates to the left. When an operand is surrounded by two ⇒ operators or by two ⇔ operators, the operand associates to the right.

∧ ∧ (( ∧ ) ∧ ))
∨ ∨ (( ∨ ) ∨ ))
⇒ ⇒ ( ⇒ ( ⇒ ))
⇔ ⇔ ( ⇔ ( ⇔ ))

Note that just because precedence allows us to delete parentheses in some cases does not mean that we can dispense with parentheses entirely. Consider the example shown earlier. Precedence eliminates the ambiguity by dictating that the sentence without parentheses is an implication with a disjunction as antecedent. However, this makes for a problem for those cases when we want to express a disjunction with an implication as a disjunct. In such cases, we must retain at least one pair of parentheses.

We end the section with two simple definitions that are useful in discussing Propositional Logic. A propositional vocabulary is a set of proposition constants. A propositional language is the set of all propositional sentences that can be formed from a propositional vocabulary.

2.3 Semantics

The treatment of semantics in Logic is similar to its treatment in Algebra. Algebra is unconcerned with the real-world significance of variables. What is interesting are the relationships among the values of the variables expressed in the equations we write. Algebraic methods are designed to respect these relationships, independent of what the variables represent.

In a similar way, Logic is unconcerned with the real world significance of proposition constants. What is interesting is the relationship among the truth values of simple sentences and the truth values of compound sentences within which the simple sentences are contained. As with Algebra, logical reasoning methods are independent of the significance of proposition constants; all that matter is the form of sentences.

Although the values assigned to proposition constants are not crucial in the sense just described, in talking about Logic, it is sometimes useful to make truth assignments explicit and to consider various assignments or all assignments and so forth. Such an assignment is called a truth assignment.

Formally, a truth assignment for a propositional vocabulary is a function assigning a truth value to each of the proposition constants of the vocabulary. In what follows, we use the digit 1 as a synonym for true and 0 as a synonym for false ; and we refer to the value of a constant or expression under a truth assignment i by superscripting the constant or expression with i as the superscript.

The assignment shown below is an example for the case of a propositional vocabulary with just three proposition constants, viz. p , q , and r .

The following assignment is another truth assignment for the same vocabulary.

Note that the formulas above are not themselves sentences in Propositional Logic. Propositional Logic does not allow superscripts and does not use the = symbol. Rather, these are informal, metalevel statements about particular truth assignments. Although talking about Propositional Logic using a notation similar to that Propositional Logic can sometimes be confusing, it allows us to convey meta-information precisely and efficiently. To minimize problems, in this book we use such meta-notation infrequently and only when there is little chance of confusion.

Looking at the preceding truth assignments, it is important to bear in mind that, as far as logic is concerned, any truth assignment is as good as any other. Logic itself does not fix the truth assignment of individual proposition constants.

On the other hand, given a truth assignment for the proposition constants of a language, logic does fix the truth assignment for all compound sentences in that language. In fact, it is possible to determine the truth value of a compound sentence by repeatedly applying the following rules.

If the truth value of a sentence is true , the truth value of its negation is false . If the truth value of a sentence is false , the truth value of its negation is true .

φ ¬φ
1 0
0 1

The truth value of a conjunction is true if and only if the truth values of its conjuncts are both true ; otherwise, the truth value is false .

φ ψ φ ∧ ψ
1 1 1
1 0 0
0 1 0
0 0 0

The truth value of a disjunction is true if and only if the truth value of at least one its disjuncts is true ; otherwise, the truth value is false . Note that this is the inclusive or interpretation of the ∨ operator and is differentiated from the exclusive or interpretation in which a disjunction is true if and only if an odd number of its disjuncts are true.

φ ψ φ ∨ ψ
1 1 1
1 0 1
0 1 1
0 0 0

The truth value of an implication is false if and only if its antecedent is true and its consequent is false ; otherwise, the truth value is true . This is called material implication .

φ ψ φ ⇒ ψ
1 1 1
1 0 0
0 1 1
0 0 1

A biconditional is true if and only if the truth values of its constituents agree, i.e. they are either both true or both false .

φ ψ φ ⇔ ψ
1 1 1
1 0 0
0 1 0
0 0 1

Using these definitions, it is easy to determine the truth values of compound sentences with proposition constants as constituents. As we shall see in the next section, we can determine the truth values of compound sentences with other compound sentences as parts by first evaluating the constituent sentences and then applying these definitions to the results.

We finish up this section with a few definitions for future use. We say that a truth assignment satisfies a sentence if and only if the sentence is true under that truth assignment. We say that a truth assignment falsifies a sentence if and only if the sentence is false under that truth assignment. A truth assignment satisfies a set of sentences if and only if it satisfies every sentence in the set. A truth assignment falsifies a set of sentences if and only if it falsifies at least one sentence in the set.

2.4 Evaluation

Evaluation is the process of determining the truth values of compound sentences given a truth assignment for the truth values of proposition constants.

As it turns out, there is a simple technique for evaluating complex sentences. We substitute true and false values for the proposition constants in our sentence, forming an expression with 1s and 0s and logical operators. We use our operator semantics to evaluate subexpressions with these truth values as arguments. We then repeat, working from the inside out, until we have a truth value for the sentence as a whole.

As an example, consider the truth assignment i shown below.

Using our evaluation method, we can see that i satisfies ( p ∨ q ) ∧ (¬ q ∨ r ).

Now consider truth assignment j defined as follows.

In this case, j does not satisfy ( p ∨ q ) ∧ (¬ q ∨ r ).

Using this technique, we can evaluate the truth of arbitrary sentences in our language. The cost is proportional to the size of the sentence. Of course, in some cases, it is possible to economize and do even better. For example, when evaluating a conjunction, if we discover that the first conjunct is false, then there is no need to evaluate the second conjunct since the sentence as a whole must be false.

2.5 Satisfaction

Satisfaction is the opposite of evaluation. We begin with one or more compound sentences and try to figure out which truth assignments satisfy those sentences. One nice feature of Propositional Logic is that there are effective procedures for finding truth assignments that satisfy Propositional Logic sentences. In this section, we look at a method based on truth tables.

A truth table for a propositional language is a table showing all of the possible truth assignments for the proposition constants in the language. The columns of the table correspond to the proposition constants of the language, and the rows correspond to different truth assignments for those constants.

The following figure shows a truth table for a propositional language with just three proposition constants ( p , q , and r ). Each column corresponds to one proposition constant, and each row corresponds to a single truth assignment. The truth assignments i and j defined in the preceding section correspond to the third and sixth rows of this table, respectively.

1 1 1
1 1 0
1 0 1
1 0 0
0 1 1
0 1 0
0 0 1
0 0 0

Note that, for a propositional language with n proposition constants, there are n columns in the truth table and 2 n rows.

In solving satisfaction problems, we start with a truth table for the proposition constants of our language. We then process our sentences in turn, for each sentence placing an x next to rows in the truth table corresponding to truth assignments that do not satisfy the sentence. The truth assignments remaining at the end of this process are all possible truth assignments of the input sentences.

As an example, consider the sentence p ∨ q ⇒ q ∧ r . We can find all truth assignments that satisfy this sentence by constructing a truth table for p , q , and r . See below. We place an x next to each row that does not satisfy the sentence (rows 2, 3, 4, 6). Finally, we take the remaining rows (1, 5, 7, 8) as answers.

   
  1 1 1  
x 1 1 0 x
x 1 0 1 x
x 1 0 0 x
  0 1 1  
x 0 1 0 x
  0 0 1  
  0 0 0  

The disadvantage of the truth table method is computational complexity. As mentioned above, the size of a truth table for a language grows exponentially with the number of proposition constants in the language. When the number of constants is small, the method works well. When the number is large, the method becomes impractical. Even for moderate sized problems, it can be tedious. Even for an application like Sorority World, where there are only 16 proposition constants, there are 65,536 truth assignments.

Over the years, researchers have proposed ways to improve the performance of truth table checking. However, the best approach to dealing with large vocabularies is to use symbolic manipulation (i.e. logical reasoning and proofs) in place of truth table checking.

2.6 Example - Natural Language

As an exercise in working with Propositional Logic, let's look at the encoding of various English sentences as formal sentences in Propositional Logic. As we shall see, the structure of English sentences, along with various key words, such as if and no , determine how such sentences should be translated.

The following examples concern three properties of people, and we assign a different proposition constant to each of these properties. We use the constant c to mean that a person is cool. We use the constant f to mean that a person is funny. And we use the constant p to mean that a person is popular.

As our first example, consider the English sentence If a person is cool or funny, then he is popular. Translating this sentence into the language of Propositional Logic is straightforward. The use of the words if and then suggests an implication. The condition ( cool or funny ) is clearly a disjunction, and the conclusion ( popular ) is just a simple fact. Using the vocabulary from the last paragraph, this leads to the Propositional Logic sentence shown below.

Next, we have the sentence A person is popular only if he is either cool or funny. This is similar to the previous sentence, but the presence of the phrase only if suggests that the conditionality goes the other way. It is equivalent to the sentence If a person is popular, then he is either cool or funny. And this sentence can be translated directly into Propositional Logic as shown below.

Finally, we have a negative sentence. There is no one who is both cool and funny. The word no here suggests a negation. To make it easier to translate into Propositional Logic, we can first rephrase this as It is not the case that there is a person who is both cool and funny. This leads directly to the following encoding.

If we have a particular truth assignment in mind, we can use the semantics of Propositional Logic to confirm that it satisfies these sentences. If we do not have a truth assignment in mind, we can use the semantics to find which truth assignments work. We discuss methods for doing these calculations later in the chapter.

Note that, just because we can translate sentences into the language of Propositional Logic does not mean that they are true. The good news is that we can use our evaluation procedure to determine which sentences are true and which are false?

Suppose we were to imagine a person who is cool and funny and popular, i.e. the proposition constants c and f and p are all true. Which of our sentences are true and which are false.

In this particular case, three of the sentences are true, while one is false. The upshot of this is that there is no such person (assuming that the theory expressed in our sentences is correct). The good news is that there are cases where all four sentences are true, e.g. a person who is cool and popular but not funny or the case of a person who is funny and popular but not cool. Question to consider: What about a person is neither cool nor funny nor popular? Is this possible according to our theory? Which of the sentences would be true and which would be false?

2.7 Example - Digital Circuits

Now let's consider the use of Propositional Logic in modeling a portion of the physical world, in this case, a digital circuit like the ones used in building computers.

The diagram below is a pictorial representation of such a circuit. There are three input nodes , some internal nodes, and two output nodes. There are five gates connecting these nodes to each other - two xor gates (the gates on the top), two and gates (the gates on the lower left), and one or gate (the gate on the lower right).

At a given point in time, a node in a circuit can be either on or off . The input nodes are set from outside the circuit. A gate sets its output either on or off based on the type of gate and the values of its input nodes. The output of an and gate is on if and only if both of its inputs are on . The value of an or node is on if and only if at least one of its inputs is on . The output of an xor gate is on if and only if its inputs disagree with each other.

Given the Boolean nature of signals on nodes and the deterministic character of gates, it is quite natural to model digital circuits in Propositional Logic. We can represent each node of a circuit as a proposition constant, with the idea that the node is on if and only if the constant is true. Using the language of Propositional Logic, we can capture the behavior of gates by writing sentences relating the values of the inputs nodes and out nodes of the gates.

The sentences shown below capture the five gates in the circuit shown above. Node o must be on if and only if nodes p and q disagree.

Once we have done this, we can use our formalization to analyze the circuit - to determine if it meets it specification, to test whether a particular instance is operating correctly, and to diagnose the problem in cases here it is not.

The syntax of Propositional Logic begins with a set of proposition constants . Compound sentences are formed by combining simpler sentences with logical operators. In the version of Propositional Logic used here, there are five types of compound sentences - negations, conjunctions, disjunctions, implications, and biconditionals. A truth assignment for Propositional Logic is a mapping that assigns a truth value to each of the proposition constants in the language. A truth assignment satisfies a sentence if and only if the sentences is true under that truth assignment according to rules defining the logical operators of the language. Evaluation is the process of determining the truth values of a complex sentence, given a truth assignment for the truth values of proposition constants in that sentence. Satisfaction is the process of determining whether or not a sentence has a truth assignment that satisfies it.

Exercise 2.1: Say whether each of the following expressions is a syntactically legal sentence of Propositional Logic.

( ) ∧ ¬
( )¬ ∨ ¬
( )¬( ∨ ) ¬ ⇒ ¬¬
( )( ∧ ) ∨ ( ¬∧ )
( ) ∨ ¬ ∧ ¬ ∨ ¬ ⇒ ∨

Exercise 2.2: Consider a truth assignment in which p is true, q is false, r is true. Use this truth assignment to evaluate the following sentences.

( ) ⇒ ∧
( ) ⇒ ∨
( ) ∧ ⇒
( ) ∧ ⇒ ¬
( ) ∧ ⇔ ∧

Exercise 2.3: A small company makes widgets in a variety of constituent materials (aluminum, copper, iron), colors (red, green, blue, grey), and finishes (matte, textured, coated). Although there are more than one thousand possible combinations of widget features, the company markets only a subset of the possible combinations. The following sentences are constraints that characterize the possibilities. Suppose that a customer places an order for a copper widget that is both green and blue with a matte coating. Your job is to determine which constraints are satisfied and which are violated.

( ) ∨ ∨
( )
( ) ∧ ¬ ⇒
( ) ∧ ¬ ⇒
( ) ∨ ⇔ ¬ ∧ ¬

Exercise 2.4: Consider the sentences shown below. There are three proposition constants here, meaning that there are eight possible truth assignments. How many of these assignments satisfy all of these sentences?

∨ ∨
⇒ ∧
⇒ ¬

Exercise 2.5: A small company makes widgets in a variety of constituent materials (aluminum, copper, iron), colors (red, green, blue, grey), and finishes (matte, textured, coated). Although there are more than one thousand possible combinations of widget features, the company markets only a subset of the possible combinations. The sentences below are some constraints that characterize the possibilities. Your job here is to select materials, colors, and finishes in such a way that all of the product constraints are satisfied. Note that there are multiple ways this can be done.

∨ ∨
∨ ∨ ∨
∧ ¬ ⇒

Exercise 2.6: Consider a propositional language with three proposition constants - mushroom , purple , and poisonous - each indicating the property suggested by its spelling. Using these proposition constants, encode the following English sentences as Propositional Logic sentences.

( )
( )
( )
( )

Exercise 2.7: Consider the digital circuit described in section 2.7. Suppose we set nodes p , q , and r to be on , and we observe that all of the other nodes are on . Running our evaluation procedure, we would see that the first sentence in our description of the circuit is not true. Hence the circuit is malfunctioning. Is there any combination of inputs p , q , and r that would result in all other nodes being on in a correctly functioning circuit? Hint: To answer this, you need consider a truth table with just eight rows (the possible values for nodes p , q , and r ) since all other nodes are observed to be on .

Once we have done this, we can check whether the circuit is operating correctly by seeing whether it behaves in accordance with our theory. We can make this determination by applying our evaluation procedure to the sentences above. If all evaluate to true, then the circuit is okay. Otherwise, something is broken.

Suppose, for example, we set nodes p , q , and r to be on. Now, suppose we observed that node o is off; and suppose we observed that all of the other nodes are on. Running our evaluation procedure, we would see that everything is okay. On the other hand, if we observed that node o is on. Running our evaluation procedure, we would see that the first sentence is false. Hence the circuit is malfunctioning.

Of course, to confirm that the circuit is fully functional, we would need to try all combinations of inputs, for each observing the values of the other nodes and checking that our sentences are true. It is tedious, but at least there is a simple procedure for doing this test.

Exercise 2.5: Victor has been murdered, and Arthur, Bertram, and Carleton are suspects. Arthur says he did not do it. He says that Bertram was the victim's friend but that Carleton hated the victim. Bertram says he was out of town the day of the murder, and besides he didn't even know the guy. Carleton says he is innocent and he saw Arthur and Bertram with the victim just before the murder. Assuming that everyone (except possibly for the murderer) is telling the truth, use evaluation to solve the crime.

Calculating the Truth Value of a Compound Proposition

  • For a conjunction to be true, both conjuncts must be true.
  • For a disjunction to be true, at least one disjunct must be true.
  • A conditional is true except when the antecedent is true and the consequent false.
  • For a biconditional to be true, the two input values must be the same (either both true or both false).
  • A negation has the opposite value of the negated proposition.
  • (A • B) is true, because both conjuncts are true.
  • ~C is false, because C is true.
  • ((A • B) ⊃ ~C) is false, because the antecedent (A • B) is true and the consequent ~C is false.

The last connective to be calculated is the main connective . The truth value of the main connective is the truth value of the compound proposition as a whole. (As you may recall, the main connective represents the logical structure of the compound proposition as a whole.) In the above example, the main connective is “⊃”, so the proposition is a conditional. Since the “⊃” is false, the proposition as a whole is false.

Calculating the truth value of a compound proposition can be challenging when the proposition is very complex. To make things easier, we can write the truth values beneath each of the letters and connectives in a compound proposition, using the numeral “1” to represent true and “0” to represent false , as shown in the example below.

((A • B) ⊃ (~C ∨ D))
1110
((A • B) ⊃ (~C ∨ D))
1 1 1010
((A • B) ⊃ (~C ∨ D))
1 1 101 0 0
((A • B) ⊃ (~C ∨ D))
1 1 1 0 01 0 0

It is often possible to calculate the truth value of a compound proposition even when the truth values of some components are unknown, as illustrated in the following example.

~(P ∨ (Q ≡ R))
1
~(P ∨ (Q ≡ R))
1 1 
~(P ∨ (Q ≡ R))
01 1 
  • 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.

How do I fix the Werror=parentheses (suggest parentheses around assignment) error?

I have a line of code which does both assignment and condition. I could split it into two lines but I'm just curious about the error message thrown.

Got this error: suggest parentheses around assignment used as truth value [-Werror=parentheses]

The error doesn't go away. But I feel I have done what I was prompted to do and added parentheses around the assignment. Why doesn't the error go away? What am I missing?

Adrian Mole's user avatar

  • 4 if((parameters->__size = m_Elements.size())) –  VLL Commented Nov 30, 2020 at 12:02
  • 2 Note that __size identifier is reserved to the language implementation, so if you define a member by that name, then behaviour of the program will be undefined. –  eerorika Commented Nov 30, 2020 at 12:06

3 Answers 3

To convince the compiler that the assignment is really what you want, you need to enclose the whole expression in parentheses, like this:

Without this, the compiler thinks that you may have made a mistake, using assignment ( = ) instead of the comparison ( == ) operator.

  • Sometimes, coding if ( ( parameters->__size = m_Elements.size() ) != 0 ) might make the code more readable –  Basile Starynkevitch Commented Nov 30, 2020 at 19:27
  • @BasileStarynkevitch I agree 100%. But, if the programmer is looking for terse code that avoids warnings, then the extra enclosing (...) is the MNC (minimal necessary change). –  Adrian Mole Commented Nov 30, 2020 at 19:31

The warning suggests you to put parentheses around the assignment expression, not around the individual operands. You can silence it via

However, ask yourself if this is really any better than the original. I suppose you turned on the warning for a reason and the suggested fix does indeed silence the warning, but the code can still cause the same confusion as before for a reader. You can do this instead:

463035818_is_not_an_ai's user avatar

The message means that you should enclose in parentheses the assignment expression.

That is instead of

you should write

Such an approach allows to distinguish a typo when instead of the comparison operator == there is typed the assignment operator = and an intentional use of the assignment in a condition.

Vlad from Moscow's user avatar

  • 1 "should have..." as in "some compiler writer thinks it's good style to...". <g> The original code is valid and its meaning is well-defined. –  Pete Becker Commented Nov 30, 2020 at 14:54

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++ c++11 or ask your own question .

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Inverses of Morphisms Necessarily Being Morphisms
  • Which cartoon episode has Green Lantern hitting Superman with a tennis racket and sending him flying?
  • Place with signs in Chinese & Arabic
  • Why did the Chinese government call its actual languages 'dialects'? Is this to prevent any subnational separatism?
  • Does the science work for why my trolls explode?
  • ASCII 2D landscape
  • I have two last names and want both Arxiv and google scholar to show them both everytime. How can I do this?
  • How can I make the curves react to the texture's values?
  • Copyright on song first performed in public
  • Using a standard junction box as a pull point in a run. Do I need to leave a loop of wire in the box or should I take the slack out?
  • Is it really a "space walk" (EVA proper) if you don't get your feet wet (in space)?
  • Will there be Sanhedrin in Messianic Times?
  • Offline autocue (teleprompter) program for Windows?
  • Solaris 11 cbe: no more updates?
  • Is Sagittarius A* smaller than we might expect given the mass of the Milky Way?
  • Coloring a function based on its monotonicity
  • Young adult fantasy book about a girl who accidentally kills her boyfriend and decides to attend an academy for witches or magic
  • If one is arrested, but has a baby/pet in their house, what are they supposed to do?
  • Browse a web page through SSH? (Need to access router web interface remotely, but only have SSH access to a different device on LAN)
  • Why is steaming food faster than boiling it?
  • Is it ok for a plugin to extend a class in some other module without declaring the other module as a dependency?
  • What's the strongest material known to humanity that we could use to make Powered Armor Plates?
  • Why does a capacitor act as an open circuit under a DC circuit?
  • Are positive definite linear operator always invertible?

c assignment truth value

IMAGES

  1. Using Truth Tables in C++ Programming

    c assignment truth value

  2. Solved Truth table in C programming

    c assignment truth value

  3. Boolean in C with Examples

    c assignment truth value

  4. Solved Consider the truth value assignment v that assigns

    c assignment truth value

  5. Answered: c. Determine the truth value of each of…

    c assignment truth value

  6. Assignment Operators in C

    c assignment truth value

VIDEO

  1. NPTEL Problem Solving through Programming in C ASSIGNMENT 6 ANSWERS 2024

  2. A Crash Course in Formal Logic Pt 7c: Truth Tables for Arguments

  3. NPTEL Problem Solving Through Programming in C Week 0 Assignment Solution July 2024 |IIT Kharagpur

  4. NPTEL Problem Solving through Programming in C ASSIGNMENT 1 Week 1 Explanation || 2024||july

  5. C Program To Find Absolute Value of a Number

  6. 84. OCR GCSE (J277) 2.4 Applying logical operators in truth tables

COMMENTS

  1. c

    2. Well you can add -Wno-parentheses (I believe that's the right one) to disable this specific warning. However, if you're that absent-minded, be careful not to write = instead of ==... - R.. GitHub STOP HELPING ICE. Mar 29, 2011 at 18:08. Possible duplicate of warning: suggest parentheses around assignment while (* (arg_to++) = * (arg_from ...

  2. c

    C++ suggest parentheses around assignment used as truth value. 0. Warning in program. 1. warning: statement with no effect wunused value. 0. Warnings when I try to output my code in C. (place parentheses around assignment to silence this warning, etc) Hot Network Questions

  3. Warning: Suggest Parentheses Around Assignment Used As Truth Value

    The -Wparentheses warning is triggered when the compiler detects an assignment used as a truth value in a conditional expression without proper parentheses. This warning is intended to help you avoid common pitfalls associated with operator precedence and improve the readability of your code. For example, consider the following code snippet ...

  4. Solution for Exercise 8-7

    The output reads 5 equals -3 because the assignment is TRUE, not because the value of variable a is -3. * The point of the exercise isn't to describe how assignments are always TRUE, but rather that you need to use two equal signs instead of one when making an "is equal to" comparison. * The compiler may warn of the assignment a=-3 (or a=5) in ...

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

    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.

  6. Assignment Expressions (GNU C Language Manual)

    7 Assignment Expressions. As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues) because they are locations that hold a value. An assignment in C is an expression because it has a value; we call it an assignment expression.

  7. Confused

    Hi all, I'm new to C and kind of confused on this. I've had a look around this group for suggestions but still not sure why the warning is occurring.

  8. C Truth value

    C Assignment = C Compound Assignment C Addition + C Subtraction - C Sign - + C Multiplication * C Division / C Operator Precedence C sizeof Operator ... C Truth value Previous Next. For C, a true expression has the value 1, and a false expression has the value 0. More generally, all nonzero values are regarded as true, and only 0 is recognized ...

  9. suggest parentheses around assignment used as truth value

    the errors come up as suggest parentheses around assignment used as truth value which it says for the lines 7,10,13,16,19 and im just wondering what it is that is wrong with it if anyone could let me know cause im new to this. heres my code: ... The = may mean "equals" in mathematics but in C and C++ it means "assignment ". The original code ...

  10. Bitwise operations in C

    1. 1. 1. The bitwise AND operator is a single ampersand: &. It is just a representation of AND which does its work on the bits of the operands rather than the truth value of the operands. Bitwise binary AND performs logical conjunction (shown in the table above) of the bits in each position of a number in its binary form.

  11. Understanding the concept of "truth assignment"

    Before introducing the concept of truth assignment, explains: Let Form(P, S) F o r m (P, S) be the set of all formulas built up from propositional variables in a set P P using connectives in a set S S which includes ∧ ∧. We shall say that a function v: Form(P, S) → {T, F} v: F o r m (P, S) → {T, F} respects the truth table ∧ ∧ if.

  12. warning: suggest parentheses around assignment used as truth value

    If you really want to use assignment as a truth value, you may enclose it in parentheses to get rid of the warning. Slawek Piotrowski Rejestracja Czasu Pracy Ewidencja Czasu Pracy. Top; AlfBaz. Author Posted: 1 Jul 2010 - 01:49 PM. Copy to clipboard to share #3. Like. 0. Dislike. 0. AlfBaz .

  13. Need help with warning message

    suggest parentheses around assignment used as truth value: and the fact is I did not change it yet, I only said.. if it was a comparison == it will give me another warning like . comparison between pointer and integer: I only want to know how can I modify this to NOT show me the warning.

  14. Introduction to Logic

    A truth assignment falsifies a set of sentences if and only if it falsifies at least one sentence in the set. 2.4 Evaluation. Evaluation is the process of determining the truth values of compound sentences given a truth assignment for the truth values of proposition constants. As it turns out, there is a simple technique for evaluating complex ...

  15. C++ suggest parentheses around assignment used as truth value

    The main problem on your side is inadvertent use of the assignment operator = instead of the intended comparison ==. On the language's side this common problem was enabled via two risk-enhancing features inherited from original C, namely that a formal condition accepts any object with a conversion to bool , and that, in support of multi ...

  16. Truth Values

    In many logic textbooks, truth values are represented using the letter "T" for true and "F" for false. This is merely a matter of convention, but there are advantages to using numerals "1" and "0" to represent truth values (as frequently done in computer science) rather than letters. Using letters to represent truth values can ...

  17. c++: truth assignment warning with arguments?

    I use the following to work with arguments in my programs, but it seems to just hand me a warning (just a warning): "warning: suggest parentheses around assignment used as truth value". The beginning of the code is as follows: while((++argv)[0] && argv[0][0]=='-'){. while(c =* ++argv[0]) The while(c =* ++argv[0]) part being where the warning ...

  18. Valuation (logic)

    In logic and model theory, a valuation can be: . In propositional logic, an assignment of truth values to propositional variables, with a corresponding assignment of truth values to all propositional formulas with those variables.; In first-order logic and higher-order logics, a structure, (the interpretation) and the corresponding assignment of a truth value to each sentence in the language ...

  19. c++

    Such an approach allows to distinguish a typo when instead of the comparison operator == there is typed the assignment operator = and an intentional use of the assignment in a condition. Share Follow