Skip to content

Instantly share code, notes, and snippets.

@Harold2017
Created October 15, 2022 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Harold2017/16ac692fd0f661a58370f33f3d1075f0 to your computer and use it in GitHub Desktop.
Save Harold2017/16ac692fd0f661a58370f33f3d1075f0 to your computer and use it in GitHub Desktop.
c++ divmod operator undefined behavior

cppreference

compiler explor

#include <cstdio>
#include <limits>

int foo(int a, int b)
{
    return b == 0 ? 0 : a % b;
}

int bar(int a, int b)
{
    return b == 0 ? 0 : (long) a % b;  // need consider both zero division and int overflow
}

int main()
{
  	printf("%d\n", foo(1, 2));
  	printf("%d\n", foo(1, 0));
    printf("%d\n", foo(-1, 3));
    //printf("%d\n", foo(std::numeric_limits<int>::min(), -1));  // error code 136

    printf("%d\n", bar(1, 2));
  	printf("%d\n", bar(1, 0));
    printf("%d\n", bar(-1, 3));
    printf("%d\n", bar(std::numeric_limits<int>::min(), -1));

    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment