Why use a statement inside an "if" statement? - if-statement

The Go tour shows an example where they have an extra statement in the same line as the "if" statement and they explain it like this: the if statement can start with a short statement to execute before the condition.
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
}
return lim
}
I don't see the need for this syntax and find it very confusing. Why not just write v := math.Pow(x, n) in the previous line?
The reason I'm asking is that for what I'm finding out, syntax finds its way into the Go language after careful consideration and nothing seems to be there out of whim.
I guess my actual question would be: What specific problem are they trying to solve by using this syntax? What do you gain by using it that you didn't have before?

There are many use cases and I do not think this feature tackles a specific problem but is rather a pragmatic solution for some problems you encounter when you code in Go. The basic intentions behind the syntax are:
proper scoping: Give a variable only the scope that it needs to have
proper semantics: Make it clear that a variable only belongs to a specific conditional part of the code
Some examples that I remember off the top of my head:
Limited scopes:
if v := computeStuff(); v == expectedResult {
return v
} else {
// v is valid here as well
}
// carry on without bothering about v
Error checking:
if perr, ok := err.(*os.PathError); ok {
// handle path error specifically
}
or more general, Type checking:
if someStruct, ok := someInterface.(*SomeStruct); ok {
// someInterface is actually a *SomeStruct.
}
Key checking in maps:
if _, ok := myMap[someKey]; ok {
// key exists
}

Because so your variables are contained in the scope
Notice that those v are declared on different scope.
A more direct example to understand scopes: http://play.golang.org/p/fInnIkG5EH
package main
import (
"fmt"
)
func main() {
var hello = "Hello"
{
hello := "This is another one"
fmt.Println(hello)
}
if hello := "New Hello"; hello != ""{
fmt.Println(hello)
}
fmt.Println(hello)
}

Related

Unexpected output in C++

This is not a problem with programming contest but with the language C++.
There is an old programming problem on codeforces. The solution is with C++. I already solved in Python but I don't understand this behavior of C++. In my computer and on onlinegdb's C++ compiler, I get expected output but on codeforces judge, I get a different output.
If interested in the problem : http://codeforces.com/contest/8/problem/A
It's very simple and a small read. Though Reading it is not required for the question.
Task in Short:
Print("forward") if string a is found in string s and string b is also found in s
Print("backward") if string a is found in reverse of string s and string b is also found in reverse of s
Print("both") if both of above are true
Print("fantasy") if both of above are false
#include<bits/stdc++.h>
using namespace std;
#define int long long
//initializing all vars because blogs said uninitialized vars sometimes give unexpected result
string s="", a="", b="";
bool fw = false;
bool bw = false;
string now="";
string won="";
int pa=-1, pb=-1, ra=-1, rb=-1;
signed main()
{
//following 2 lines can be ignored
ios_base::sync_with_stdio(false);
cin.tie(NULL);
//taking main input string s and then two strings we need to find in s are a & b
cin >> s >> a >> b;
//need reverse string of s to solve the problem
string r = s;
reverse(r.begin(), r.end());
//pa is index of a if a is found in s else pa = -1 if not found
pa = s.find(a);
//if a was a substring of s
if (pa != -1) {
//now is substring of s from the next letter where string a was found i.e. we remove the prefix of string till last letter of a
now = s.substr(pa + a.size(), s.size() - (pa + a.size()));
//pb stores index of b in remaining part s i.e. now
pb = now.find(b);
//if b is also in now then fw is true
if (pb != -1) {
fw = true;
}
}
//same thing done for the reverse of string s i.e. finding if a and b exist in reverse of s
ra = r.find(a);
if (ra != -1) {
won = r.substr(ra + a.size(), r.size() - (ra + a.size()));
rb = won.find(b);
if (rb != -1) {
bw = true;
}
}
if (fw && bw) {
cout << "both" << endl;
}
else if (fw && !bw) {
cout << "forward" << endl;
}
else if (!fw && bw) {
cout << "backward" << endl;
}
else {
cout << "fantasy" << endl;
}
return 0;
}
For input
atob
a
b
s="atob", a="a", b="b"
Here reverse of atob is bota.
a is in atob.
So, string now = tob.
b is in tob so fw is true.
Now a is in bota.
So, string won = "" (empty because nothing after a). So, b is not in won.
So, rw is false.
Here answer is to print forward and in C++14 on my PC and onlinegdb, the output is forward but on codeforces judge, it's both.
I did many variations of the code but no result.
Finally I observed that if I run my program on PC and don't give any input and terminate the program in terminal with Ctrl-C, it prints both which is strange as both should only be printed when both fw and rw are true.
What is this behavior of C++?
Let's dissect this code and see what problems we can find. It kind of tips over into a code review, but there are multiple problems in addition to the proximate cause of failure.
#include<bits/stdc++.h>
Never do this. If you see it in an example, you know it's a bad example to follow.
using namespace std;
Fine, we're not in a header and brevity in sample code is a reasonable goal.
#define int long long
Oh no, why would anyone ever do this? The first issue is that preprocessor replacement is anyway prohibited from replacing keywords (like int).
Even without that prohibition, this later line
int pa=-1, pb=-1, ra=-1, rb=-1;
is now a deliberate lie, as if you're obfuscating the code. It would have cost nothing to just write long long pa ... if that's what you meant, and it wouldn't be deceptive.
//initializing all vars because blogs said uninitialized vars sometimes give unexpected result
string s="", a="", b="";
But std::string is a class type with a default constructor, so it can't be uninitialized (it will be default-initialized, which is fine, and writing ="" is just extra noise).
The blogs are warning you about default initialization of non-class types (which leaves them with indeterminate values), so
bool fw = false;
is still sensible.
NB. these are globals, which are anyway zero-initialized (cf).
signed main()
Here are the acceptable faces of main - you should never type anything else, on pain of Undefined Behaviour
int main() { ... }
int main(int argc, char *argv[]) { ... }
Next, these string positions are both (potentially) the wrong type, and compared to the wrong value:
ra = r.find(a);
if (ra != -1) {
could just be
auto ra = r.find(a);
if (ra != std::string::npos) {
(you could write std::string::size_type instead of auto, but I don't see much benefit here - either way, the interface, return type and return values of std::string::find are well-documented).
The only remaining objection is that none of now, won or the trailing substring searches correspond to anything in your problem statement.
The above answer and comments are way more enough information for your question. I cannot comment yet so I would like to add a simplified answer here, as I'm also learning myself.
From the different outputs on different compilers you can trackback the logic and found the flow of code is differ in this line:
if (rb != -1) {
Simply adding a log before that line, or using a debugger:
cout << "rb:" << rb << endl;
You can see that on your PC: rb:-1
But on codeforces: rb:4294967295
won.find(b) return npos, which mean you have an assignment: rb = npos;
This is my speculation, but a possible scenario is:
On your PC, rb is compiled as int (keyword), which cannot hold 4294967295, and assigned to -1.
But on codeforces, rb is compiled as long long, follow the definition, and 4294967295 was assigned instead.
Because you redefine the keyword int, which is advised again by standard of C++ programming language, different compiler will treat this line of code differently.

mockito: Verification in order failure: twice the same

I face the following:
Verification in order failure
Wanted but not invoked:
commandExecutor.execute(
src/test/resources,
isNull(),
"pdflatex",
["-interaction=nonstopmode", "-synctex=1", "-src-specials", "-recorder", "-shell-escape", "-output-format=pdf", "test.tex"],
src/test/resources/test.pdf
);
-> at org.m2latex.core.LatexProcessorTest.verifyRunLatex(LatexProcessorTest.java:700)
Wanted anywhere AFTER following interaction:
commandExecutor.execute(
src/test/resources,
null,
"pdflatex",
["-interaction=nonstopmode", "-synctex=1", "-src-specials", "-recorder", "-shell-escape", "-output-format=pdf", "test.tex"],
src/test/resources/test.pdf
);
-> at org.m2latex.core.LatexProcessor.runLatex2dev(LatexProcessor.java:1304)
What I do not understand is, that Mockito seems to see something
looking for me as really the same as wanted, but seemingly is not.
What is the reason???
The code is as follows:
this.inOrderExec.verify(this.executor, atLeastOnce())
.execute(eq(WORKING_DIR),
isNull(),
eq(this.settings.getLatex2pdfCommand()),
eq(LatexProcessor.buildLatexArguments
(this.settings,
this.settings.getPdfViaDvi(),
this.texFile)),
eq(this.dviPdfFile));
I verified also: The code works if I write
verify(this.executor, atLeastOnce())
i.e. without ordering.
I can post more code if necessary, of course.
Update: it seems as if this problem occurs if and only if
I cannot remove the , atLeastOnce() argument.
Maybe this is a valuable hint for someone out there....
Update:
I found out, that in a method either all verify's work with inOrder like that:
this.inOrder.verify(this.fileUtils).matchInFile
or neither does.
Special case:
private void verifyConstrLatexMainDesc() {
// FIXME: doubling from mockConstrLatexMainDesc()
String[] suffixes = new String[] {
LatexProcessor.SUFFIX_VOID,
LatexProcessor.SUFFIX_PDF,
"."+this.settings.getPdfViaDvi().getLatexLanguage(),
LatexProcessor.SUFFIX_LOG,
LatexProcessor.SUFFIX_IDX,
LatexProcessor.SUFFIX_IND,
LatexProcessor.SUFFIX_ILG,
LatexProcessor.SUFFIX_GLS,
LatexProcessor.SUFFIX_GLO,
LatexProcessor.SUFFIX_GLG
};
for (int idx = 0; idx < suffixes.length; idx++) {
//this.inOrder.
//if (idx == 1 ||idx == 2) {continue;}
verify(this.fileUtils, atLeastOnce())
.replaceSuffix(this.texFile, suffixes[idx]);
}
}
Ok, I see that this works if indices 1 and 2 are left out.
Then one can also leave away atLeastOnce()
I suspect that the problem is that a new string is created, right?
or that in my case, two arguments are '.pdf'
The other methods which work only for atLeastOnce()
are so that they are invoked more than once.
Is this a valuable hint?

Parse error in code: expected ' ; ' before ' { ' token -- what is causing this?

The error I'm getting is error: expected ' ; ' before ' { ' token
I tried fixing the code by adding ; after if (thisisanumber==5) as well as after else (thisisanumber!=5). While this solves the first error it creates another error that says error: ' else ' without a previous ' if '. I'd really love to know what error I've made in writing the code, thanks.
Here is my code:
#include <iostream>
using namespace std;
int main()
{
int thisisanumber;
cout<<"Whats the Password?: ";
cin>> thisisanumber;
cin.ignore();
if (thisisanumber==5) {
cout<<"You've discovered the password! Wow, you're a genious you should be proud./n";
}
else (thisisanumber!=5) {
cout<<"You've failed in knowing the password and therefore cannot enter, leave and do not come back. Goodbye!/n";
}
cin.get();
}
You're missing a keyword if:
else if (thisisanumber!=5) {
^^
Alternately, since the opposite condition to thisisanumber == 5 is that thisisanumber is not 5, you don't need the condition:
else {
You don't need another condition as there are only two cases - just use else { ... } and it will catch all cases in which thisisanumber==5 is false.
The structure of an if statement is:
if (condition) { ... }
else if (another condition) { ... }
// ... more conditions
else { ... all cases in which no previous condition matched end up here ... }
... but the else if and else parts are always optional.
What happens is the compiler looks at the following:
else (thisisanumber!=5) {
and thinks to itself:
"OK, here's else. Is the next token if? No. Ok, so this is an else clause, and the next thing is what to do in the else-case. Is the next token {? No. Ok, so in the else-case, we execute a single statement, instead of a block. Is the next token (? Yes. Ok, so our statement is wrapped in parentheses... [insert here: the rest of the thought process for interpreting an expression that's wrapped in parentheses] Ok, there's the matching ). Whew. Now let's just match up the ; for this statement... wait, what's this? A {! That's not right."
The compiler is reading the code one token at a time, left to right. It does not report an error at the point where, in a logical sense that humans understand, the error actually is. It reports an error at the point where, by reading the code one token at a time, left to right, it is first able to detect that something is wrong.
It would be legal to write else (thisisanumber!=5);. That would mean "if the number is not equal to 5 (because the if test failed), then check if the number is not equal to 5, and do nothing with the result of that comparison". Meaningless, but legal. It would also be legal to write else if (thisisanumber!=5) {...}, which is presumably what you meant. That would mean "if the number is not equal to 5 (because the if test failed), and the number is not equal to 5, then do this stuff inside the {}". But this is redundant: given that something is not equal to 5, it is guaranteed to be not equal to 5, so there is no point in specifying the test twice. So we should just write else {...}.
"else" is really a shorter word for "otherwise", and has that purpose in C++ as well.

Why are empty expressions legal in C/C++?

int main()
{
int var = 0;; // Typo which compiles just fine
}
How else could assert(foo == bar); compile down to nothing when NDEBUG is defined?
This is the way C and C++ express NOP.
You want to be able to do things like
while (fnorble(the_smurf) == FAILED)
;
and not
while (fnorble(the_smurf) == FAILED)
do_nothing_just_because_you_have_to_write_something_here();
But! Please do not write the empty statement on the same line, like this:
while (fnorble(the_smurf) == FAILED);
That’s a very good way to confuse the reader, since it is easy to miss the semicolon, and therefore think that the next row is the body of the loop. Remember: Programming is really about communication — not with the compiler, but with other people, who will read your code. (Or with yourself, three years later!)
I'm no language designer, but the answer I'd give is "why not?" From the language design perspective, one wants the rules (i.e. the grammar) to be as simple as possible.
Not to mention that "empty expressions" have uses, i.e.
for (i = 0; i < INSANE_NUMBER; i++);
Will dead-wait (not a good use, but a use nonetheless).
EDIT: As pointed out in a comment to this answer, any compiler worth its salt would probably not busy wait at this loop, and optimize it away. However, if there were something more useful in the for head itself (other than i++), which I've seen done (strangely) with data structure traversal, then I imagine you could still construct a loop with an empty body (by using/abusing the "for" construct).
OK, I’ll add this to the worst case scenario that you may actually use:
for (int yy = 0; yy < nHeight; ++yy) {
for (int xx = 0; xx < nWidth; ++xx) {
for (int vv = yy - 3; vv <= yy + 3; ++vv) {
for (int uu = xx - 3; uu <= xx + 3; ++uu) {
if (test(uu, vv)) {
goto Next;
}
}
}
Next:;
}
}
I honestly don't know if this is the real reason, but I think something that makes more sense is to think about it from the standpoint of a compiler implementer.
Large portions of compilers are built by automated tools that analyze special classes of grammars. It seems very natural that useful grammars would allow for empty statements. It seems like unnecessary work to detect such an "error" when it doesn't change the semantics of your code. The empty statement won't do anything, as the compiler won't generate code for those statements.
It seems to me that this is just a result of "Don't fix something that isn't broken"...
Obviously, it is so that we can say things like
for (;;) {
// stuff
}
Who could live without that?
When using ;, please also be aware about one thing. This is ok:
a ? b() : c();
However this won't compile:
a ? b() : ; ;
There are already many good answers but have not seen the productive-environment sample.
Here is FreeBSD's implementation of strlen:
size_t
strlen(const char *str)
{
const char *s;
for (s = str; *s; ++s)
;
return (s - str);
}
The most common case is probably
int i = 0;
for (/* empty */; i != 10; ++i) {
if (x[i].bad) break;
}
if (i != 10) {
/* panic */
}
while (1) {
; /* do nothing */
}
There are times when you want to sit and do nothing. An event/interrupt driven embedded application or when you don't want a function to exit such as when setting up threads and waiting for the first context switch.
example:
http://lxr.linux.no/linux+v2.6.29/arch/m68k/mac/misc.c#L523

Checking lists and running handlers

I find myself writing code that looks like this a lot:
set<int> affected_items;
while (string code = GetKeyCodeFromSomewhere())
{
if (code == "some constant" || code == "some other constant") {
affected_items.insert(some_constant_id);
} else if (code == "yet another constant" || code == "the constant I didn't mention yet") {
affected_items.insert(some_other_constant_id);
} // else if etc...
}
for (set<int>::iterator it = affected_items.begin(); it != affected_items.end(); it++)
{
switch(*it)
{
case some_constant_id:
RunSomeFunction(with, these, params);
break;
case some_other_constant_id:
RunSomeOtherFunction(with, these, other, params);
break;
// etc...
}
}
The reason I end up writing this code is that I need to only run the functions in the second loop once even if I've received multiple key codes that might cause them to run.
This just doesn't seem like the best way to do it. Is there a neater way?
One approach is to maintain a map from strings to booleans. The main logic can start with something like:
if(done[code])
continue;
done[code] = true;
Then you can perform the appropriate action as soon as you identify the code.
Another approach is to store something executable (object, function pointer, whatever) into a sort of "to do list." For example:
while (string code = GetKeyCodeFromSomewhere())
{
todo[code] = codefor[code];
}
Initialize codefor to contain the appropriate function pointer, or object subclassed from a common base class, for each code value. If the same code shows up more than once, the appropriate entry in todo will just get overwritten with the same value that it already had. At the end, iterate over todo and run all of its members.
Since you don't seem to care about the actual values in the set you could replace it with setting bits in an int. You can also replace the linear time search logic with log time search logic. Here's the final code:
// Ahead of time you build a static map from your strings to bit values.
std::map< std::string, int > codesToValues;
codesToValues[ "some constant" ] = 1;
codesToValues[ "some other constant" ] = 1;
codesToValues[ "yet another constant" ] = 2;
codesToValues[ "the constant I didn't mention yet" ] = 2;
// When you want to do your work
int affected_items = 0;
while (string code = GetKeyCodeFromSomewhere())
affected_items |= codesToValues[ code ];
if( affected_items & 1 )
RunSomeFunction(with, these, params);
if( affected_items & 2 )
RunSomeOtherFunction(with, these, other, params);
// etc...
Its certainly not neater, but you could maintain a set of flags that say whether you've called that specific function or not. That way you avoid having to save things off in a set, you just have the flags.
Since there is (presumably from the way it is written), a fixed at compile time number of different if/else blocks, you can do this pretty easily with a bitset.
Obviously, it will depend on the specific circumstances, but it might be better to have the functions that you call keep track of whether they've already been run and exit early if required.