---
title: "C++: Tricky codes"
description: "This are my collections of c++ codes which are very tricky. Some of them I found by making mistakes,..."
author: "Madiyar92"
published: "2015-09-07T15:40:25+00:00"
modified: "2015-09-16T16:46:27+00:00"
locale: "ru"
canonical_url: "https://yvision.kz/post/c-tricky-codes-537309"
markdown_url: "https://yvision.kz/post/c-tricky-codes-537309/markdown"
site_name: "Yvision.kz"
---

# C++: Tricky codes

> This are my collections of c++ codes which are very tricky. Some of them I found by making mistakes,...

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?

 

1: A - B

- #include

- using namespace std;
- int main() {

- int a = 020;
- short b = 2;
- cout

- using namespace std;
- int main() {

- bool ok = true;

- // Try to guess with if condition \

- if (!ok && true)

- cout

- using namespace std;
- int main() {

- unsigned a = 0;
- int b = 2;
- if (a + b >= -2)

- cout ="

- using namespace std;
- int main() {

- int a = 0, b = 1;
- if (a&b==0) {

- cout

- using namespace std;
- int main() {

- long long a = 1e18 + 1;
- cout

- using namespace std;
- int main(){

- string s ="a";
- for(int i =0; i

- using namespace std;
- int main() {

- bool ok = true;

- // Try to guess with if condition if (!ok && true)

- cout =-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:** "100000000000000000**0**" instead of "100000000000000000**1**". 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.

---

Source: [https://yvision.kz/post/c-tricky-codes-537309](https://yvision.kz/post/c-tricky-codes-537309)