Note that I've considered the question like a challenge or a puzzle. Do not consider this answer good C practice. Obviously the cleanest way to make a sum of 2 values from input is to use 2 variables. I still find the challenge interesting though.
#include <stdio.h>
#include <math.h>
int main()
{
int a;
printf("%g", fmin((scanf("%d", &a), a), 1.0/0.0 + rand()) + fmin((scanf("%d", &a), a), 1.0/0.0 + rand()));
return 0;
}
Works with negative values.
I'm using the comma operator which executes both expressions but only return the second one. So (scanf("%d", &a), a)
is like calling scanf("%d", &a)
and returns a
. I pass this result through a function (any function) as I want to prevent updating the value (to sum it with the new a). I have no idea if your compiler will call the left or right part of the big expression first but it doesn't matter as both are doing the same thing. Whichever executes first will be the first value from input.
fmin(x, 1.0/0.0 + rand())
makes sure nothing is inlined by the compiler. 1.0/0.0 is Infinity and would never be returned in fmin()
in our case. Compiler would inline this to x
normally but adding + rand()
to Infinity (which is still Infinity) seems to prevent it.
You can even do it by declaring "0" variable by using argc:
#include <stdio.h>
#include <math.h>
int main(int a)
{
printf("%g", fmin((scanf("%d", &a), a), 1.0/0.0 + rand()) + fmin((scanf("%d", &a), a), 1.0/0.0 + rand()));
return 0;
}
I've used this to test: https://www.onlinegdb.com/online_c_compiler