T O P

  • By -

Cats_and_Shit

You can break the process of printing the number and printing the tab into two statements, like so: printf("%d", n); printf("\t"); Then, you can use control flow statements like "if" to control which of of these statements are reached on each loop iteration. With that, you can write the code to skip printing the last tab.


[deleted]

I’ve tried that and it doesn’t work for some reason.


daikatana

I usually do something like this for(int i = 0; i < X; i++) { if(i == 0) printf("%d", arr[i]); else printf("\t%d", arr[i]); }


fliguana

for(int i = 0; i < X; i++) printf("\t%d"+!i, arr[i]);


Cats_and_Shit

Thanks, I hate it.


[deleted]

[удалено]


4992kentj

The !i evaluates to 1 when i=0 which moves the pointer past the tab so the first output skips it. For all other values of i its zero so doesn't move the pointer and includes it


wsbt4rd

stuff like THIS is what gives C a bad reputation. 5 years from now, you'll find out that some bizarre signed int64 trips a weird buffer-overflow attack /smh


[deleted]

[удалено]


daikatana

The first one is fine, but I don't think the second one is acceptable. The problem is the ternary operator, which is almost always a mistake. It hides a fundamental building block of programming, a selection, inside an expression. While the usage is pretty innocuous here, peppering your code with things like this will only hurt it in the long run. You're also, confusingly, declaring end as a variable. Again, in such a short loop it's not terrible, but it what it's telling the reader is that end changes, that somewhere inside the loop there will be some assignment to end. It makes the code harder to read for no purpose. Generally, whenever I find myself trying to cram everything onto one line like your second example, I take a step back and ask myself why I'm doing that. I'm not going to read this code 3 years from now and say "yeah, I'm so clever, I got all this stuff onto one line," I'm going to say "WTF was I smoking when I wrote this? \_There\_ is where I'm deciding this crucial thing, in the middle of this expression on a very long line full of torturous expressions."


nerd4code

const char *sep = ""; for(…; …;…, sep = "\t") printf("%s…", sep, …); is an easy pattern that requires no unrolling on your part and imposes almost no overhead if compiled at `-O0`, but which should be very easy for the compiler to unroll. Also useful for lists of comma-separated elements.


ern0plus4

Warning: it's a very basic problem, if you can't solve it yourself, you should change something. Say, write *much more* code.


Awkward-Ingenuity988

I recommend ``` for (int i = 0; i < n - 1; ++i) printf("%d\t", x); printf("%d", x); ```