+ 1

What is this code at line 6?

#include <stdio.h> #include <iostream> using namespace std; void update(int *a,int *b) { int sum = *a + *b; int absDifference = *a - *b > 0 ? *a - *b : -(*a - *b); //here what is going on?? *a = sum; *b = absDifference; } int main() { int a, b; int *pa = &a, *pb = &b; scanf("%d %d", &a, &b); update(pa, pb); printf("%d\n%d", a, b); return 0; }

23rd Mar 2022, 2:24 AM
Haris
Haris - avatar
3 Respostas
+ 3
It is finding the absolute value of the difference. A more readable version might look like this: absDifference = *a - *b; if (absDifference<0) absDifference = -absDifference;
23rd Mar 2022, 2:59 AM
Brian
Brian - avatar
+ 1
It's within the update() function. It's has pointers a and b. Saves their sum to variable sum It's using ternary to do a sort of if-else assignment of absDifference variable. Checks if a - b is positive assigns a - b, else assigns -(a -b) //negative of a negative is a positive. Then copies sum to the address pointed to by a Copies absDifference to the address pointed to by b No return for that function.
23rd Mar 2022, 4:27 AM
HungryTradie
HungryTradie - avatar