GCCã®ä¸å¯è§£ãªæåã«æ©ã¾ããã¦ããã以ä¸ã®ã³ã¼ãã¯ãè² æ°ãåºåããªããã¨ãæå¾ ããããã-O2以ä¸ã®æé©åãããã¨è² æ°ãåºåããã¦ãã¾ãã
#include <cstdint> #include <cstdio> int main(int argc, char** argv) { constexpr uint32_t modulo = 2039; for (int32_t i = 0; i < 65536; i++) { const int32_t result = static_cast<uint32_t>(i * i) % modulo; std::printf("%d\n", result); } return 0; }
ä¸è¨ã§ãi ã®å¤ã46340ãè¶ ããã¨ãi * i ã®å¤ãint32_tã®ç¯å²ããªã¼ãã¼ããã¼ãã¦è² æ°ã«ãªãããã®ç´å¾ã«uint32_tã«ãã£ã¹ããããã¨æ£æ°ã«å¤æããããã®å¾ã«2039ã§å²ã£ãä½ãã«ãªãã®ã§ãçµæã¯0ãã2038ã®éã«ãªãã¯ãã ããããint32_tã«ãã£ã¹ããã¦ããªã¼ãã¼ããã¼ã¯ããªãã¯ãã ã-O0ã¨-O1ã§ã¯æå¾ éãã«åä½ããããããã-O2以ä¸ã®æé©åãããã¨ãè² æ°ãçæãããã-O2以ä¸ã®æé©åãããå ´åããå¤æ°moduloã®å®£è¨ã«volatileãã¤ããã¨è² æ°ã¯çæãããªãã
gccã®ãã¼ã¸ã§ã³ã¯gcc (Ubuntu 10.3.0-1ubuntu1~20.10) 10.3.0ã ããã°ãªã®ããä»æ§ä¸ã§æªå®ç¾©ã®æåãå¼ãèµ·ããè¨è¿°ããã¦ãã¾ã£ã¦ããã®ããããããªãããã£ã¹ããç¡è¦ããã¦ããã®ã¯ã¢ã»ã³ããªåºåãè¦ãã¾ã§ããªãæãããªã®ã ãããªããããªãã®ãã¨ããããä»æ§éããªã®ãã©ãããç¥ãããããæé©åã«ãã£ã¦ãã£ã¹ããç¡è¦ããããã¨ããããã¨ããäºå®ãèªããã¨ããã¨ãã©ã®ãããªå ´åã«ãããèµ·ããã®ãç¥ã£ã¦ãããªãã¨å®å¿ãã¦æ®ãããªãã ããããåç¥ã®äººããããæãã¦ã»ããã
追è¨ï¼æ å ±ãå¯ãã¦ããã ãããこのページã«ããã¨ãunsignedã®ãªã¼ãã¼ããã¼ã¯2ã®è£æ°ã®çµæãå¾ãããããsignedã®å ´åã«ã¯ä½ãèµ·ãã£ã¦ããããããªããããããªã¼ãã¼ããã¼ãã該å½ã®æ¼ç®ã®å¤ãæªå®ç¾©ã«ãªãã ãã§ãªããå¤å´ã®ãã£ã¹ãæ¼ç®ãå«ãã¦æåãå¤ããã¨ã¯ãæããããsignedã®ãªã¼ãã¼ããã¼ã¯çºçãããæç¹ã§è² ãã£ã¦ãã¨ãããªã¼ãã¼ããã¼ããªããã¨ãåæã¨ãã¦æé©åãè¡ãã°ããã£ã¹ããæ¶ããã®ã¯èªç¶ã¨ãè¨ãããã ã¨ããã°ãããããä¸å®ã«ãªããèªåã®éå»ã®ã³ã¼ããæ´ã£ã¦ãsignedã®ãªã¼ãã¼ããã¼ã®æãããªãã確èªããã°ã