vak: (Знайка)
[personal profile] vak
На собеседованиях я часто спрашиваю программистов, как сложить на Си два целых числа. Проверим, как с этим справится Гугл Бард.
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.cc
If 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.

Ну что сказать. Искусственный интеллект становится реальным помощником программисту.

Date: 2023-04-25 06:42 (UTC)
ordinary_joe_backup: (Default)
From: [personal profile] ordinary_joe_backup
Складываем два интеджера и возвращаем макс инт если переполнилось? Не, ну как пример кода ок, но как это можно практически использовать то?

Date: 2023-04-25 07:41 (UTC)
ordinary_joe_backup: (Default)
From: [personal profile] ordinary_joe_backup
Ну я вот про ерунду и задумался, потому что какой смысл складывать если оно вылетит в переполнение? Значит дизайн плохой в первую очередь!

Date: 2023-04-25 08:53 (UTC)
From: [personal profile] ex0_planet
А какой здесь может быть хороший? Wrap around даёт на выходе мусорные данные неотличимые от валидных, разрядная сетка пошире не всегда (чаще всего) недоступна, разные NAN и исключения тоже неприменимы из-за особенностей вычислительного конвейера. Еще варианты?

Date: 2023-04-25 09:09 (UTC)
ordinary_joe_backup: (Default)
From: [personal profile] ordinary_joe_backup
и вот как ответственный девелопер это я и должен озвучить архитекту. пусть думает что в его дизайне не так, ему за это деньги платят )))

Date: 2023-04-25 09:13 (UTC)
From: [personal profile] ex0_planet
В problem domain где подобные техники актуальны, вот это ваше "озвучить архитекту" эквивалентны одиночной итальянской забастовке. С соответствующими оргвыводами.

Date: 2023-04-25 09:32 (UTC)
ordinary_joe_backup: (Default)
From: [personal profile] ordinary_joe_backup
возможно. в моем приземленном домейне и проблем таких не возникает обычно.

Date: 2023-04-25 09:26 (UTC)
tiresome_cat: (CuriousCat)
From: [personal profile] tiresome_cat
Ну почему сразу плохой дизайн? Верифицировать (нормализовать) входящие данньіе всегда полезно для здоровья, а если их генерирует человек - даже необходимо. Против дурака архитектура бессильна. Классика же: "мусор на вход е - мусор на вьіходе".
Edited Date: 2023-04-25 09:30 (UTC)

Date: 2023-04-25 09:33 (UTC)
ordinary_joe_backup: (Default)
From: [personal profile] ordinary_joe_backup
я млохо могу себе представить реалистичную задачу под это решение в любом случае, мусор там на входе или нет.

Date: 2023-04-25 09:47 (UTC)
tiresome_cat: (CuriousCat)
From: [personal profile] tiresome_cat
Чой-то? Вот, например, суммирование двух PCM-coded зуковьіх потоков. Там ограничение максимального значения как раз вьіглядит вполне естественно. Наличие в вьіходном потоке значений +/- INT_MAX при єтом может бьіть основанием для аппаратной регулировки уровня входного сигнала. Но уже в другой функции :)
Edited Date: 2023-04-25 09:54 (UTC)

Date: 2023-04-25 11:50 (UTC)
ordinary_joe_backup: (Default)
From: [personal profile] ordinary_joe_backup
далеко от моей предметной области :)

Date: 2023-04-25 10:38 (UTC)
pritkiy_kaban: (Default)
From: [personal profile] pritkiy_kaban
Показывать студентам как пример: вот что бывает, когда сделано корректно, а прилететь может как с датчиком температуры на TMI :)

Date: 2023-04-25 11:50 (UTC)
ordinary_joe_backup: (Default)
From: [personal profile] ordinary_joe_backup
вот вот