Thanks to @DialFrost for drawing my attention to this question.
I believe for reading 4 numbers your solution is optimal. However, I found a solution that saves bytes when reading 5 or more numbers at a time.
It will also consume the entire input (i.e. it can't be used in a loop).
Depending on the context it might help you with only 4 variables too
If you define your variables in a sequence like this:
a,b,c,d,e;main(){
In this case, the variables will be layed out in successive memory addresses, we can abuse that.
for(;~scanf("%d",&a+e);e++);
Full program:
// new
a,b,c,d,e;main(){for(;~scanf("%d",&a+e);e++);}
// original
a,b,c,d;main(e){scanf("%d%d%d%d""%d%d%d%d%d",&a,&b,&c,&d,&e);}
This 29 byte segment will paste all the input in successive variables starting in a
. We re-use e
, (the last variable) as the index variable. This saves declaring one variable.
Size comparison
Number of inputs | Original | New | Original (full program) | new (full program) |
---|---|---|---|---|
1 | 14 | 28 | 24 | 38 |
2 | 19 | 28 | 31 | 40 |
3 | 24 | 28 | 38 | 42 |
4 | 29 | 28 | 45 | 44 |
5 | 34 | 28 | 52 | 46 |
6 | 39 | 28 | 59 | 48 |
Note that the new method gains a 1 byte disadvantage in full programs because you can't use function arguments, however, this doesn't matter if you can use another variable as the argument to main
.
Note there is also a slot in the initialization portion of the for loop. If you can put another expression there this method can save 1 byte even with only 4 arguments.
@JDT ponted out you can save 1 byte at the cost of having 1 added to e
at the end:
for(;0<scanf("%d",&a+e++););