C++: Tricky codes
This are my collections of c++ codes which are very tricky.
Some of them I found by making mistakes, so recorded them to avoid making the same bug twice.
Try to guess the output just by reading, please don't use any compiler or IDE.
Do you know other tricky codes?
-
#include <iostream>
-
using namespace std;
-
int main() {
-
int a = 020;
-
short b = 2;
-
cout << a - b << endl;
-
return 0;
-
}
-
#include <iostream>
-
using namespace std;
-
int main() {
-
bool ok = true;
-
// Try to guess with if condition \
-
if (!ok && true)
-
cout << "I am ok" << endl;
-
return 0;
-
}
-
#include <iostream>
-
using namespace std;
-
int main() {
-
unsigned a = 0;
-
int b = 2;
-
if (a + b >= -2)
-
cout << a + b << ">=" << -2 << endl;
-
else
-
cout << a + b << "<" << -2 << endl;
-
return 0;
-
}
-
#include <iostream>
-
using namespace std;
-
int main() {
-
int a = 0, b = 1;
-
if (a&b==0) {
-
cout << (a&b) << "=" << 0 << endl;
-
} else {
-
cout << (a&b) << "!=" << 0 << endl;
-
}
-
return 0;
-
}
-
#include <iostream>
-
using namespace std;
-
int main() {
-
long long a = 1e18 + 1;
-
cout << a << endl;
-
return 0;
-
}
-
#include <iostream>
-
using namespace std;
-
int main(){
-
string s ="a";
-
for(int i =0; i <= s.size()-2;++i)
-
cout << s[i]<<" ";
-
return0;
-
}
Upd.
Answers:
1. Output: "14". Because 020 is in octal base, therefore 16 - 2 = 14
2. Output: "I am ok". When you use "\", it means that you split one long line to several lines.
So, for a compiler the code looks like this:
-
#include <iostream>
-
using namespace std;
-
int main() {
-
bool ok = true;
-
// Try to guess with if condition if (!ok && true)
-
cout << "I am ok" << endl;
-
return 0;
-
}
3. Output: "2<-2". The reason is: unsigned int + int = unsigned int,
i.e unsigned type has higher priority than int when it comes to casting.
Thus, a + b is unsigned.
-
if(2>=-2)// i.e unsigned >= int
In a result compiler casts both parts to unsigned. As a consequence, the line turns into:
-
if (2 >= 4294967294)
but wait, why 4294967294? Numbers are stored in binary form. Negative number are stored in what's called two's complement. The two's complement of an n-bit number x is 2^n-x.
Thus, 2^32 - 2 = 4294967294.
4. Output: "0!=0". Because "==" has higher priority. Advice : look into priority table or always put brackets.
5. Output: "1000000000000000000" instead of "1000000000000000001". Because of the representation of float.
6. Output: Runtime Error. Because, s.size() returns "size_t" type which is unsigned integer type. So, s.size() - 2 is unsigned, so it turns into a huge number. In a result, runtime error because it tries to access non-existing index.
