incorrect clion warning for 'condition always false' - c++

I just coded this in my c++ project in clion
int step_size_x = someValue;
int step_size_y = anotherValue;
while (!(step_size_x == 1 && step_size_y == 1)) {
step_size_x = (step_size_x != 1) ? (step_size_x / 2) : step_size_x;
step_size_y = (step_size_y != 1) ? (step_size_y / 2) : step_size_y;
}
and clion gives me a warning, that the second statement (line 5) in my while loop step_size_y != 1 will always be false.
I could not comprehend how it comes to that conclusion so I quickly threw this into a c++ online shell - and it seemes to side with me.
Since I do not have that much experience with c++ I really am not convinced to have found a bug and am rather tending towards that the answer is stupefying obvious. In that case, please enlighten me, what am I missing here?
Note:
step_size_y will be set external files, therefore the compiler should be able to predict its value. Anyway, if it was 1 the warning would appear in the second half of the while()'s brackets.
Here is a screenshot of the warning:

Related

Autohotkey If Statement makes only one result

I wanted to run a program on working day only,
so I wrote a AutoHotKey script to check "today is sunday or holiday"
But my script doesn't work and I didn't get what the problem is.
Here is the code.
Result = "WorkingDay"
if(A_Wday = 1) {
Result = "Sunday"
}
HolidayList = 0101|0211|0212|0213|0301|0409|0501|0505|0519|0606|0815|0920|0921|0922|1003|1009|1225
StringSplit,HoliDay,HoliDayList,|
StringLeft,Today,A_Now,8
StringRight,Today,Today,4
Loop %Holiday0%
{
CheckDay := HoliDay%A_index%
; msgbox, %Today% = %CheckDay%
if ( %Today% == %CheckDay% ) {
Result = "Holiday"
break
}
}
msgbox, %Today% = %Result%
The problem is that the "Result" variable return only "Holiday"
Please help me out......... Thanks in advance.
Basically you're just using a whole bunch of legacy code, and trying to mix in some modern non-legacy stuff, and they really don't mix well unless you know very well how to do it.
Biggest issue is this right here:
if ( %Today% == %CheckDay% )
By trying to use the legacy way of referring to variables in a non legacy if ()(docs), bad things happen. You're trying to use dynamic variables, and you really don't want that, so what actually happens is that you check if nothing == nothing, and that's always going to return true.
How you're actually supposed to refer to variables in a modern expression statement, is just
if (Today = CheckDay)
(when comparing, = and == are for case insensitive and case sensitive comparing, you probably meant to do =)
And now it should work.
Here's the whole code in modern AHK:
Result := "WorkingDay"
if (A_Wday = 1)
Result := "Sunday"
HolidayList := "0101|0211|0212|0213|0301|0409|0501|0505|0519|0606|0815|0920|0921|0922|1003|1009|1225"
Holidays := StrSplit(HolidayList, "|")
Today := SubStr(A_Now, 5, 4)
for each, Holiday in Holidays
{
if (Today = Holiday)
{
Result := "Holiday"
break
}
}
MsgBox, % Today " = " Result
I don't have time to explain it more right now, but to learn about legacy vs modern AHK, I recommend this documentation page and this previous answer of mine:
https://www.autohotkey.com/docs/Language.htm
When to use % or %variable% in AutoHotKey?

Weird Compiler behavior (C++)

I'm trying to add GA library (GALib) to my error-free program, when I add it, the compiler returns strange errors and repeat them so many times... For an example, "syntax error: missing '{' before '<' " is returned for the first line of the following template code:
template<class _Ty>
_Check_return_ inline _Ty _Pow_int(_Ty _Xx, int _Yx) _NOEXCEPT
{
unsigned int _Nx;
if (_Yx >= 0)
_Nx = static_cast<unsigned int>(_Yx);
else
_Nx = static_cast<unsigned int>(-_Yx);
for (_Ty _Zx = static_cast<_Ty>(1); ; _Xx *= _Xx)
{
if ((_Nx & 1) != 0)
_Zx *= _Xx;
if ((_Nx >>= 1) == 0)
return (_Yx < 0 ? static_cast<_Ty>(1) / _Zx : _Zx);
}
}
The error is in cmath.h
The error is repeated for the same line like for 25 times or so. The same for so many others. (The mentioned error is the first one on the list)
PS. I added the GA files using the following sequence:
1- Project properties>C++>Additional include libraries>select folder
2- Drag-Drop the folder containing the headers and sources to the project solution manager
PPS. All source files are with extension .C not .cpp
How can I solve such situation?
Following procedures in this page: msdn.microsoft.com/en-us/library/032xwy55.aspx Most errors just vanished (including the mentioned one).
The main problem was that the compiler deals with .C files with default option, which I changed to C++ as mentioned in aforementioned page.

Optimize ternary operator

I came across this code written by someone else. Is this usage of the conditional operator recommended or commonly used? I feel it is less maintainable - or is it just me? Is there any alternate way of writing this?
exp_rsp_status = req.security_violation ? (dis_prot_viol_rsp && is_mstr) ?
uvc_pkg::MRSP_OKAY : uvc_pkg::MRSP_PROTVIOL : req.slv_req.size() ?
((is_mst_abort_rsp && dis_mst_abort_rsp) ||
((req.slv_req[0].get_rsp_status()==uvc_pkg::MRSP_PROTVIOL) && dis_prot_viol_rsp) ||
(is_mst_abort_rsp && req.is_pci_config_req() && dis_pcicfg_mst_abort_rsp)) ?
uvc_pkg::MRSP_OKAY : req.slv_req[0].get_rsp_status() : uvc_pkg::MRSP_OKAY;
That's just horrible code.
It's badly formatted. I don't see the hierarchy of the expression.
Even if it had good formatting, the expression would be way too complex to quickly parse with the human eye.
The intention is unclear. What's the purpose of those conditions?
So what can you do?
Use conditional statements (if).
Extract the sub-expressions, and store them in variables. Check this nice example from the refactoring catalog.
Use helper functions. If the logic is complex, use early returns. Nobody likes deep indentation.
Most importantly, give everything a meaningful name. The intention should be clear why something has to be calculated.
And just to be clear: There's nothing wrong with the ternary operator. If used judiously, it often produces code that's easier to digest. Avoid nesting them though. I occasionally use a second level if the code is crystal clear, and even then I use parentheses so my poor brain doesn't have to do extra cycles decyphering the operator precedence.
Care about the readers of your code.
Perhaps this is in a device driver's message loop and the original coder, possibly 10 years ago, didn't want jumps in the code. I hope he verified that his compiler didn't implement the ternary operator with jumps!
Examining the code, my first remark is that a sequence of ternary operators is -- like all code -- better readable when adequately formatted.
That said, I'm not sure that I parsed the OP's example correctly, which speaks against it. Even a traditional nested if-else construct would be hard to verify. This expression violates the fundamental programming paradigm: Divide and Conquer.
req.security_violation
? dis_prot_viol_rsp && is_mstr
? uvc_pkg::MRSP_OKAY
: uvc_pkg::MRSP_PROTVIOL
: req.slv_req.size()
? is_mst_abort_rsp && dis_mst_abort_rsp
|| req.slv_req[0].get_rsp_status()==uvc_pkg::MRSP_PROTVIOL
&& dis_prot_viol_rsp
|| is_mst_abort_rsp && req.is_pci_config_req() && dis_pcicfg_mst_abort_rsp
? uvc_pkg::MRSP_OKAY
: req.slv_req[0].get_rsp_status()
: uvc_pkg::MRSP_OKAY;
I wanted to check how the code looks when refactored. It sure is not shorter but I like how the speaking function names make the intent clearer (of course I guessed here). This is, to some degree, pseudo code because the variable names are probably not global so that the functions would have to have parameters, making the code less clear again. But perhaps the parameter could be a single pointer to a status or request structure or such (from which values like dis_prot_viol_rsp have been extracted). Whether or not to use a ternary when combining the different conditions is up to debate. I find it often elegant.
bool ismStrProtoViol()
{
return dis_prot_viol_rsp && is_mstr;
}
bool isIgnorableAbort()
{
return is_mst_abort_rsp && dis_mst_abort_rsp;
}
bool isIgnorablePciAbort()
{
return is_mst_abort_rsp && req.is_pci_config_req() && dis_pcicfg_mst_abort_rsp;
}
bool isIgnorableProtoViol()
{
return req.slv_req[0].get_rsp_status()==uvc_pkg::MRSP_PROTVIOL && dis_prot_viol_rsp;
}
eStatus getRspStatus()
{
eStatus ret;
if( req.security_violation )
{
ret = ismStrProtoViol() ? uvc_pkg::MRSP_OKAY : uvc_pkg::MRSP_PROTVIOL;
}
else if( req.slv_req.size() )
{
ret = isIgnorableAbort()
|| isIgnorableProtoViol()
|| isIgnorablePciAbort()
? uvc_pkg::MRSP_OKAY
: req.slv_req[0].get_rsp_status();
else
{
ret = uvc_pkg::MRSP_OKAY;
}
return ret;
}
Finally we can exploit the fact that uvc_pkg::MRSP_OKAY is kindof the default and only overwritten under certain circumstances. This eliminates a branch. Look how after some chiseling the code's reasoning is nicely visible: If it's not a security violation look closer and check the actual request status, minus empty requests and ignorable aborts.
eStatus getRspStatus()
{
eStatus ret = uvc_pkg::MRSP_OKAY;
if( req.security_violation )
{
ret = ismStrProtoViol() ? uvc_pkg::MRSP_OKAY : uvc_pkg::MRSP_PROTVIOL;
}
else if( req.slv_req.size()
&& !isIgnorableAbort()
&& !isIgnorableProtoViol()
&& !isIgnorablePciAbort()
)
{
ret = req.slv_req[0].get_rsp_status();
}
return ret;
}
What an ugly mess. I broke it out into if and else's just to see what it was doing. Not much more readable, but thought I'd post it anyways. Hopefully someone else has a more elegant solution for you. But to answer your question, don't use ternaries that complicated. No one wants to do what I just did to figure out what it's doing.
if ( req.security_violation )
{
if ( dis_prot_viol_rsp && is_mstr )
{
exp_rsp_status = uvc_pkg::MRSP_OKAY;
}
else
{
exp_rsp_status = uvc_pkg::MRSP_PROTVIOL;
}
}
else if ( req.slv_req.size() )
{
if ( ( is_mst_abort_rsp && dis_mst_abort_rsp ||
( req.slv_req[0].get_rsp_status() == uvc_pkg::MRSP_PROTVIOL && dis_prot_viol_rsp ) ||
( is_mst_abort_rsp && req.is_pci_config_req() && dis_pcicfg_mst_abort_rsp ) )
{
exp_rsp_status = uvc_pkg::MRSP_OKAY;
}
else
{
exp_rsp_status = req.slv_req[0].get_rsp_status();
}
}
else
{
exp_rsp_status = uvc_pkg::MRSP_OKAY
}
This is terrible code.
While it is often desirable to initialize a variable with a single expression (for example, so we can make it const), this is no excuse to write code like this. You can move the complex logic into a function and call it to initialize the variable.
void
example(const int a, const int b)
{
const auto mything = make_my_thing(a, b);
}
In C++11 and later, you can also use a lambda to initialize a variable.
void
example(const int a, const int b)
{
const auto mything = [a, b](){
if (a == b)
return MyThing {"equal"};
else if (a < b)
return MyThing {"less"};
else if (a > b)
return MyThing {"greater"};
else
throw MyException {"How is this even possible?"};
}();
}
Others already said how awful that code excerpt is, with nice explanations. I will just provide few more reasons why that code is bad :
if you consider one "if-else" to implement exactly one feature, then it is clear how complex that code is. In your case, I can not even count number of ifs.
It is obvious that your code is breaking breaking the single responsibility principle, which tells :
...a class or module should have one, and only one, reason to change.
unit testing that would be a nightmare, which is another red flag. And I bet that your colleague didn't even try to write unit tests for that piece of code.
Common or recommended? No.
I did something similar, but I had my reasons:
It was an argument into a third-party C function.
I was not well versed in modern C++ at the time.
I commented and formatted the f*** out of it because I knew SOMEONE besides me was going to read it...or I needed to know what it was doing years later.
It was DEBUG CODE that was never going into a release.
textprintf_ex(gw->GetBackBuffer(), font, 0, 16, WHITE, -1, "BUTTON: %s",
//If... Then Display...
(ButtonClicked(Buttons[STOP]) ? "STOP"
: (ButtonClicked(Buttons[AUTO]) ? "AUTO"
: (ButtonClicked(Buttons[TICK]) ? "TICK"
: (ButtonClicked(Buttons[BLOCK]) ? "BLOCK"
: (ButtonClicked(Buttons[BOAT]) ? "BOAT"
: (ButtonClicked(Buttons[BLINKER]) ? "BLINKER"
: (ButtonClicked(Buttons[GLIDER]) ? "GLIDER"
: (ButtonClicked(Buttons[SHIP]) ? "SHIP"
: (ButtonClicked(Buttons[GUN]) ? "GUN"
: (ButtonClicked(Buttons[PULSAR]) ? "PULSAR"
: (ButtonClicked(Buttons[RESET]) ? "RESET"
: /*Nothing was clicked*/ "NONE"
)))))))))))
);
The only reason I did not use an if-else chain was it would have made the code immense and harder to follow because all I needed to do was print a word to the screen.

else if comparison - compiler standpoint

Are these blocks of code identical? By identical I mean, does the compiler interpret them exactly the same way?
int i = 2;
if (i == 0) {
System.out.println("0!");
} else if (i == 1) {
System.out.println("1!");
} else if (i == 2) {
System.out.println("2!");
} else {
System.out.println("?!");
}
int i = 2;
if (i == 0) {
System.out.println("0!");
} else {
if (i == 1) {
System.out.println("1!");
} else {
if (i == 2) {
System.out.println("2!");
} else {
System.out.println("?!");
}
}
}
As you can see this is Java.
While both my friend and I agree that logically these are exactly the same, I was wondering whether the java compiler compiles them exactly the same way. The thing that strikes me is that in the second else/if block you are nesting ifs and elses inside of the else block.
However, given my lack of knowledge in assembly or java byte code, this very well could compile to be completely identical. The only advantage could be syntactical sugar, if you will.
Will someone put this issue to rest - assuming you are extremely confident in the answer (otherwise another debate might ensue).
The two code samples differ only in the use of redundant curly braces, so I would be very suprised if different code is generated. But it's easy enough to check if you are really curious - use the javap command to display the bytecode.

Simple if statement not evaluating to true when it should

if ((!m_pMediaPage->PageLayer() || !m_pMediaPage->LoadState()) &&
!m_pMediaPage->m_bRequestList)
{
GetListInfo();
m_pMediaPage->m_bRequestList = TRUE;
}
GetListInfo() does not get executed when all values are 0.
PageLayer() and LoadState() return ints and m_bRequestList is an int.
Basically rewritten as this:
if ((!0 || !0) && !0) -or- if ((1 || 1) && 1)
I can only assume that the values being evaluated by the if statement aren't really as seen by the debugger.
I am using visual studio 2005 and put breakpoints on line 1 & 4 to examine the values and see if it executes into the if statement. I am not sure how else to debug this.
Like I said, each of the 3 values are 0 as viewed by the debugger when at breakpoint 1.
Functions in .h:
int PageLayer() {return m_iCurrentLayer;} - protected
BOOL LoadState() {return m_bLoadDone;} - protected
BOOL:
typedef int BOOL;
This conditional statement looks as if it would be executed if all values return from the different functions return zero. If the body of the function isn't executed, I would debug the problem as follows:
Log the values of all functions prior to the if-statement:
std::cout << "page-layer=" << !m_pMediaPage->PageLayer() << ' '
<< "load-state=" << !m_pMediaPage->LoadState() << ' '
<< "request-list=" << !m_pMediaPage->m_bRequestList << '\n';
Yes, the debugger should show these values as well but I have great faith in the values being printed to be the values actually evaluated.
If that doesn't give the necessary insight into what goes wrong, I would start breaking down the condition into separate parts and verify success at each level, e.g.:
if (!m_pMediaPage->PageLAyer()) {
std::cout << "page-layer is not set\n";\
}
if (!m_pMediaPAge->LoadState()) {
std::cout << "load-state is not set\n";
...
If this still doesn't give any insight, I'd start suspecting that the functions return funny values and I would verify that the different results are funny values and I would start looking at the output after preprocesing using the -E option.
You tagged the question as VS2005; do you have all relevant service packs installed to ensure you aren't running into some long-fixed compiler issue?
Secondly, the functions you've listed appear to be very simple setters (you might want to make them const, although that is unrelated to your problem).
You're stepping thru with the debugger, it might therefore be valuable to check your assertion that they are all zero:
bool plCond = (m_pMediaPage->PageLayer());
bool lsCond = (m_pMediaPage->LoadState());
bool rlCond = (m_pMediaPage->m_bRequestList);
bool getListInfoCond = ((!cond1 || !cond2) && !cond3);
if (getListInfoCond)
{
GetListInfo();
m_pMediaPage->m_bRequestList = TRUE;
}
If this fixes the problem, you either have a heisenbug or a stack/memory stomp.
If this doesn't fix the problem, it may home in on the cause.
If this DOES fix the problem, you may want to consult the assembly for the code and see if you have somehow tripped a compiler bug.