C++ Notes: Array Initialization has a nice list over initialization of arrays. I have a
int array[100] = {-1};
expecting it to be full with
Should be a standard feature but for some reason it's not included in standard C nor C++...
#include
__asm__
(
" .global _arr; "
" .section .data; "
"_arr: .fill 100, 1, 2; "
);
extern char arr[];
int main()
{
int i;
for(i = 0; i < 100; ++i) {
printf("arr[%u] = %u.\n", i, arr[i]);
}
}
In Fortran you could do:
program main
implicit none
byte a(100)
data a /100*2/
integer i
do i = 0, 100
print *, a(i)
end do
end
but it does not have unsigned numbers...
Why can't C/C++ just implement it. Is it really so hard? It's so silly to have to write this manually to achieve the same result...
#include
#include
/* did I count it correctly? I'm not quite sure. */
uint8_t arr = {
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
};
int main()
{
int i;
for(i = 0; i < 100; ++i) {
printf("arr[%u] = %u.\n", i, arr[i]);
}
}
What if it was an array of 1,000,00 bytes? I'd need to write a script to write it for me, or resort to hacks with assembly/etc. This is nonsense.
It's perfectly portable, there's no reason for it not to be in the language.
Just hack it in like:
#include
#include
/* a byte array of 100 twos declared at compile time. */
uint8_t twos[] = {100:2};
int main()
{
uint_fast32_t i;
for (i = 0; i < 100; ++i) {
printf("twos[%u] = %u.\n", i, twos[i]);
}
return 0;
}
One way to hack it in is via preprocessing... (Code below does not cover edge cases, but is written to quickly demonstrate what could be done.)
#!/usr/bin/perl
use warnings;
use strict;
open my $inf, "out.c";
my @lines = <$inf>;
foreach my $line (@lines) {
if ($line =~ m/({(\d+):(\d+)})/) {
printf ("$1, $2, $3");
my $lnew = "{" . "$3, "x($2 - 1) . $3 . "}";
$line =~ s/{(\d+:\d+)}/$lnew/;
printf $ouf $line;
} else {
printf $ouf $line;
}
}
close($ouf);
close($inf);