c++ Why is this true and not false? - c++

I'm trying to understand why ! ( ( true || false ) && false ) is true and not false but I can't seem to figure it out.

true || false == true
true && false == false
!false == true

! ( ( true || false ) && false )
is equal to
! ( ( true ) && false )
which is
! ( false )
which is
true

Try to go through it one-by-one:
! ( ( true || false ) && false )
3 ( ( 1 ) 2 )
1) true || false => true because it is true if at least either of them is true.
2) true && false => false because it is only true if both are true, i.e. if at least either of them is false, it evaluates to false.
3) !(false) => true because '!' means negation, the negation of false is true, and the negation of true is false.

For these kind of Boolean logic issues I always try to break it into steps.
So for this the first condition
( true || false )
This is equal to true as you're saying true OR false
The next condition can now be read as
( true && false )
Which is false
The final bit that makes it true as oppssed to false is the !
The final part can be equated to
!( false )
The ! flips the value so the final statement is true

Related

Is there a way to split logical conditions on new lines?

for example I want to have my line length at 120 - so generally code is only wrapped after 120 chars. But more often then not we want to have our logcal conditions on new lines:
I have the follow expression:
if ((long_function_name_12345().get_some_status1() != status1) ||
(long_function_name_12345().get_some_status2() != status2) ||
force ||
some_other_logical_bool)
{
}
When I clang-format it I get:
if ((long_function_name_12345().get_some_status1() != status1) ||
(long_function_name_12345().get_some_status2() != status2) || force || some_other_logical_bool)
{
}
Which is not as nice. I want the behaviour to be, once we go over the column limit (120 in this case) then break on any logical block. I have found one way to force it:
if ((long_function_name_12345().get_some_status1() != status1) ||
(long_function_name_12345().get_some_status2() != status2) || // break
force || // break
some_other_logical_bool)
{
}
It's a bit crap but works but is (IMO) less ugly then wrapping it in // clang-format off/on tags...
clang-format version 10.0.0-4ubuntu1~18.04.2
.clang-format contents:
---
Language: Cpp
# BasedOnStyle: WebKit
AccessModifierOffset: -4
AlignAfterOpenBracket: AlwaysBreak
AlignConsecutiveMacros: false
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Right
AlignOperands: false
AlignTrailingComments: false
AllowAllArgumentsOnNextLine: false
AllowAllConstructorInitializersOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
# Don't allow function on one line, e.g. 'int f() {return 1;}' - unless its inline
AllowShortFunctionsOnASingleLine: InlineOnly
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine
BinPackArguments: false
BinPackParameters: false
BraceWrapping:
AfterCaseLabel: true
AfterClass: true
AfterControlStatement: true
AfterEnum: true
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: true
AfterStruct: true
AfterUnion: true
AfterExternBlock: true
BeforeCatch: true
BeforeElse: true
IndentBraces: true
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
# have line breaks after operators: 'if (a ||' instead of on the next line ' || b'
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Allman
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeComma
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
# effectively the line length limit before clang-format starts to use multiple lines
ColumnLimit: 120
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
# format braces lists (uniform init) like a function param list
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: false
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
- Regex: '.*'
Priority: 1
SortPriority: 0
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentCaseLabels: true
IndentGotoLabels: true
IndentPPDirectives: None
IndentWidth: 4
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 4
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
# 'int *p' instead of 'int* p;'
PointerAlignment: Right
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: true
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInConditionalStatement: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
Standard: Latest
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 8
UseCRLF: false
UseTab: Never
...
I could not find anything obvious for this - and maybe its a bit too specific.
This is the best I could find / come up with (as noted in my updated question):
if ((long_function_name_12345().get_some_status1() != status1) ||
(long_function_name_12345().get_some_status2() != status2) || // break
force || // break
some_other_logical_bool)
{
}
i.e. by adding some sort of comment it forces clangformat to not merge the lines

How can clang-format don't put if statements into one line?

Just like the code below, I use clang-format to automatic format my codes
if(detectBeats[*beatsCont-2] > detectBeats[*beatsCont-1]
|| fabs(detectBeats[*beatsCont-2] > detectBeats[*beatsCont-1]) < 1.0)
{
*beatsCont -=1;
}
Whatever I set the .clang-formt file, it always formatted like this:
if(detectBeats[*beatsCont-2] > detectBeats[*beatsCont-1] || fabs(detectBeats[*beatsCont-2] > detectBeats[*beatsCont-1]) < 1.0)
{
*beatsCont -=1;
}
How can I set the rules not wrap the if statements into oneline?
My question isn't as that question(Clang format splits if statement body into multiple lines), b/c my if statement wrapped, not the body
Here is my .clang-format file
AccessModifierOffset : -4
AllowAllParametersOfDeclarationOnNextLine : false
AlignEscapedNewlinesLeft : false
AlignOperands: true
AlignTrailingComments : true
AllowShortCaseLabelsOnASingleLine: true
AllowShortFunctionsOnASingleLine: false
AllowShortIfStatementsOnASingleLine : true
AllowShortLoopsOnASingleLine: true
BinPackArguments : false
BinPackParameters : false
BreakBeforeBraces : Linux
ColumnLimit: 0
CommentPragmas: '^ *\/\/'
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
IndentWidth : 4
KeepEmptyLinesAtTheStartOfBlocks : false
Language : Cpp
MaxEmptyLinesToKeep : 2
ObjCBlockIndentWidth : 2
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList : false
PointerAlignment: Right
ReflowComments: true
SortIncludes: true
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators : true
SpaceBeforeParens : ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments : 1
SpacesInAngles: false
SpacesInContainerLiterals : false
SpacesInParentheses : false
SpacesInSquareBrackets: false
Standard: Cpp11
UseTab : Never
You need to use ColumnLimit. Doc here. More method here

In Sass, how to compare two or more values in if statement?

I know that in PHP I can do something like this:
if ($foo == true && $bar == true) {
// Both true
} elseif ($foo == false && $bar == false) {
// Both false
}
How could I do that in Sass? Or can I... The docs are sparse on this topic http://sass-lang.com/documentation/file.SASS_REFERENCE.html#_6
I tried something like this:
#if $foo == false $bar == false {
// Both false
}
Doesn't give error but it only evaluates the $foo.
This also wont work:
#if $foo == false && $bar == false {
// Both false
}
Nor this:
#if $foo == false AND $bar == false {
// Both false
}
Thanks!
From ยง6.4.4 - Boolean Operations:
SassScript supports and, or, and not operators for boolean values.

How to set python variables to true or false?

I want to set a variable in Python to true or false. But the words true and false are interpreted as undefined variables:
#!/usr/bin/python
a = true;
b = true;
if a == b:
print("same");
The error I get:
a = true
NameError: global name 'true' is not defined
What is the python syntax to set a variable true or false?
Python 2.7.3
First to answer your question, you set a variable to true or false by assigning True or False to it:
myFirstVar = True
myOtherVar = False
If you have a condition that is basically like this though:
if <condition>:
var = True
else:
var = False
then it is much easier to simply assign the result of the condition directly:
var = <condition>
In your case:
match_var = a == b
match_var = a==b
that should more than suffice
you cant use a - in a variable name as it thinks that is match (minus) var
match=1
var=2
print match-var #prints -1
Python boolean keywords are True and False, notice the capital letters. So like this:
a = True;
b = True;
match_var = True if a == b else False
print match_var;
When compiled and run, this prints:
True
you have to use capital True and False not true and false
as Poke said:
If you have a condition that is basically like this though:
if <condition>:
var = True
else:
var = False
then it is much easier to simply assign the result of the condition
directly:
var = <condition>
but if you want to reverse it you can use:
var = <condition> is False

Memcpy unexpected behavior

I'm coding my own version of Tetris. While creating blockRotation method I encountered weird problem with memcpy. During second call for blockRotate, my bool[4*4] array is not saved corectly, despite that is generated properly. What's wrong?
This is my error log:
arr_shift[0]: true
arr_shift[1]: false
arr_shift[2]: false
arr_shift[3]: false
arr_shift[4]: true
arr_shift[5]: true
arr_shift[6]: false
arr_shift[7]: false
arr_shift[8]: true
arr_shift[9]: false
arr_shift[10]: false
arr_shift[11]: false
arr_shift[12]: false
arr_shift[13]: false
arr_shift[14]: false
arr_shift[15]: false
arr_rot[0]: false
arr_rot[1]: false
arr_rot[2]: true
arr_rot[3]: false
arr_rot[4]: false
arr_rot[5]: false
arr_rot[6]: true
arr_rot[7]: true
arr_rot[8]: false
arr_rot[9]: false
arr_rot[10]: true
arr_rot[11]: false
arr_rot[12]: false
arr_rot[13]: false
arr_rot[14]: false
arr_rot[15]: false
shape[0]: true
shape[1]: false
shape[2]: false
shape[3]: false
shape[4]: true
shape[5]: true
shape[6]: false
shape[7]: false
shape[8]: true
shape[9]: false
shape[10]: false
shape[11]: false
shape[12]: false
shape[13]: false
shape[14]: false
shape[15]: false
arr_shift[0]: false
arr_shift[1]: false
arr_shift[2]: false
arr_shift[3]: false
arr_shift[4]: false
arr_shift[5]: false
arr_shift[6]: false
arr_shift[7]: false
arr_shift[8]: false
arr_shift[9]: false
arr_shift[10]: false
arr_shift[11]: false
arr_shift[12]: false
arr_shift[13]: false
arr_shift[14]: false
arr_shift[15]: false
arr_rot[0]: false
arr_rot[1]: true <---
arr_rot[2]: true <---
arr_rot[3]: true <---
arr_rot[4]: false
arr_rot[5]: false
arr_rot[6]: true <---
arr_rot[7]: false
arr_rot[8]: false
arr_rot[9]: false
arr_rot[10]: false
arr_rot[11]: false
arr_rot[12]: false
arr_rot[13]: false
arr_rot[14]: false
arr_rot[15]: false
shape[0]: false
shape[1]: false <---
shape[2]: false <---
shape[3]: false <---
shape[4]: false
shape[5]: false
shape[6]: false <---
shape[7]: false
shape[8]: false
shape[9]: false
shape[10]: false
shape[11]: false
shape[12]: false
shape[13]: false
shape[14]: false
shape[15]: false
And this is my code:
memset(shape, 0, 16*sizeof(bool));
if(toShift == true) {
memcpy(shape, arr_shift, 16*sizeof(bool));
}
else {
memcpy(shape, arr_rot, 16*sizeof(bool));
}
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
fprintf(stderr, "shape[%i]: %s\n", i*4+j, shape[i*4+j]? "true":"false" );
}
}
fprintf(stderr, "\n\n");
Declararation of shape is in Block class header, and is as follows:
bool shape[16];
You haven't shown us where arr_rot is declared or what value toShift is. However, most likely either toShift is true or you declared where arr_rot points to on the stack in another function.