LoginSignup
35
8

More than 3 years have passed since last update.

C++でa == 1 && a == 2 && a == 3をtrueにしてみたい(クソ解法)

Last updated at Posted at 2019-09-23

先駆者

https://qiita.com/yumetodo/items/bbeed7258cd22fd8bb7c
https://qiita.com/fujitanozomu/items/e4ab6f20837ed8234cd3
https://qiita.com/shiozaki/items/fe3ee5a4775e5ca19f20

動機

https://qiita.com/fujitanozomu/items/e4ab6f20837ed8234cd3#comment-9ec3137b3bd475eed044
このコメントを見てて思いついた

「未定義動作でもできる?じゃん?」

しかし乗るネタが古いな?

よい子はマネしないでね

#include <iostream>

int func(volatile int a) {
    if (a == 1 && a == 2 && a == 3) {
        return 42;
    } else {
        return a/0;
    }
}

bool func2(int x) {
    return func(x) == 42;
}

int main()
{
    std::cout << std::boolalpha;
    std::cout << func2(0) << std::endl;
    std::cout << func2(1) << std::endl;
    std::cout << func2(2) << std::endl;
    std::cout << func2(3) << std::endl;
}

結果

true
true
true
true

バイナリ

一部抜粋

func2(int):
        mov     eax, 1
        ret

素晴らしいですね!

35
8
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
8