У Барда я спрашивал
2023-04-24 15:45На собеседованиях я часто спрашиваю программистов, как сложить на Си два целых числа. Проверим, как с этим справится Гугл Бард.
Please create a function "int add(int a, int b)", which adds two integer numbers and avoids undefined behavior.Мгновенный ответ:
Sure, here is the C function int add(int a, int b) that adds two integer numbers and avoids undefined behavior:За последние несколько лет ни от кого из сапиенсов я не получал настолько быстрый и исчерпывающий ответ. Но продолжим:int add(int a, int b) { int sum; /* Check for overflow */ if (a > 0 && b > 0 && (a > INT_MAX - b)) { /* Overflow detected */ return INT_MAX; } else if (a < 0 && b < 0 && (a < INT_MIN - b)) { /* Overflow detected */ return INT_MIN; } /* Add the two numbers */ sum = a + b; return sum; }This function first checks for overflow by comparing the two numbers to the maximum and minimum values for an integer. If either number is greater than the maximum value or less than the minimum value, then the function returns INT_MAX or INT_MIN, respectively. Otherwise, the two numbers are added together and the result is returned.
This function avoids undefined behavior by checking for overflow before adding the two numbers. If overflow is detected, the function returns a safe value instead of crashing or producing unexpected results.
Please create a few tests for this function.Пауза чуть подольше:
Sure, here are a few tests for the add() function:Неплохо, но я же дотошный, продолжаю усугублять.#include <stdio.h> int add(int a, int b); int main() { int expected, actual; /* Positive numbers */ expected = 10; actual = add(5, 5); if (expected != actual) { printf("add(5, 5) expected %d, got %d\n", expected, actual); return 1; } /* Negative numbers */ expected = -10; actual = add(-5, -5); if (expected != actual) { printf("add(-5, -5) expected %d, got %d\n", expected, actual); return 1; } /* Overflow */ expected = INT_MAX; actual = add(INT_MAX - 1, 1); if (expected != actual) { printf("add(INT_MAX - 1, 1) expected %d, got %d\n", expected, actual); return 1; } /* Underflow */ expected = INT_MIN; actual = add(INT_MIN + 1, -1); if (expected != actual) { printf("add(INT_MIN + 1, -1) expected %d, got %d\n", expected, actual); return 1; } return 0; }These tests cover a variety of cases, including positive numbers, negative numbers, overflow, and underflow. If all of these tests pass, then it is likely that the add() function is working correctly.
Please use Googletest for tests.Этого Барда ничем не проймёшь.
Sure, here are the same tests written using GoogleTest:#include <gtest/gtest.h> int add(int a, int b); TEST(AddTest, Positive) { EXPECT_EQ(10, add(5, 5)); } TEST(AddTest, Negative) { EXPECT_EQ(-10, add(-5, -5)); } TEST(AddTest, Overflow) { EXPECT_EQ(INT_MAX, add(INT_MAX - 1, 1)); } TEST(AddTest, Underflow) { EXPECT_EQ(INT_MIN, add(INT_MIN + 1, -1)); }These tests are written using the GoogleTest framework, which provides a more structured and organized way to write tests. The EXPECT_EQ() macro asserts that the two arguments are equal. If they are not equal, the test will fail.
These tests can be run using the gtest command-line tool. For example, to run all of the tests, you would use the following command:gtest add_test.ccIf all of the tests pass, then the output will be:[==========] Running 4 tests from 1 test case. [----------] Global test environment set-up. [----------] 4 tests from AddTest [ RUN ] AddTest.Positive [ OK ] AddTest.Positive (0 ms) [ RUN ] AddTest.Negative [ OK ] AddTest.Negative (0 ms) [ RUN ] AddTest.Overflow [ OK ] AddTest.Overflow (0 ms) [ RUN ] AddTest.Underflow [ OK ] AddTest.Underflow (0 ms) [----------] 4 tests from AddTest (0 ms total) [----------] No test cases ran. [----------] No assertions have been violated. [==========] 4 tests passed.
Ну что сказать. Искусственный интеллект становится реальным помощником программисту.

no subject
Date: 2023-04-28 11:56 (UTC)Это решение хорошо для языковых пуристов и архитектурных астронавтов, бесконечно спорящих о гипотетических процессорах, где отрицательные целые числа не представлены в дополнительном коде или где по умолчанию применяется суммирование с насыщением.
На практике обычно бывает по-другому: надо заставить чёртов компилятор вставить самую обычную инструкцию ADD (которая работает максимально быстро и с учётом представления в дополнительном коде реализуется в железе одинаково для сложений со знаком и для сложений без знака), за которой просто проверить вычисленный в железе флаг переполнения (который называется OF в случае x86 и amd64, когда идёт речь о сложении со знаком; для засекания переполнения при беззнаковых сложениях есть другой флаг, CF).
И это делается через __builtin_add_overflow: https://godbolt.org/z/j6MEMKcr6
А если начать выдрючиваться с проверкой знаков операндов, вычитанием из INT_MIN и прочими подобными выкрутасами, то даже если не ошибёшься по типу off-by-one error во всех этих условиях, то компилятор налепит кучу ветвлений, которые, как говорится, ни к селу, ни к городу: https://godbolt.org/z/737c6fxea
Если мы пишем на абстрактном Си для абстрактного процессора и самое главное не расстроить Его Величество Стандарт, то это решение как бы окэй (хотя с первого взгляда отсутствие off-by-one errors во всех этих условиях неочевидно, что впрочем компенсируется тестами); а если к списку требований добавляется ещё и приемлемая производительность готового решения, то задачка становится уже совсем другой: как заставить чёртов компилятор вставить инструкцию для самого обычного сложения, а затем достать из процессора те флаги, которые он уже и так "на халяву" для нас вычислил в результате этого самого обычного сложения.
no subject
Date: 2023-04-29 22:00 (UTC)