commit 514da6e code中文原文

Printing a Diamond in One Line

Author
Yujia Lin
Date
Reading time
1 min read

Translated from Chinese by Claude. Read the original

I first saw this on pwhack‘s blog. He wrote it in Go, but for a classic exercise like this there are lots of ways to do it in C. So I wanted to see just how short the simplest version of this problem could get. And then I found this snippet

1
2
3
4
5
6
7
8
9
10
11
12
13
#include "stdio.h"

int line = 1;

int main() {

printf("%s\n",7-(line>4? line-4: 4-line),"**"+2*(line>4? line-4:4-line));

if(++line != 8) main();

return 0;

}

You might be wondering: what’s the * doing in printf()?

Actually, * is a modifier, and you can use it in both scanf() and printf(). In scanf, * means skip… For example:

scanf("%*d %*d %d",&n;); printf("%d",n);

So when you type 1 2 3, only n gets stored, and it prints 3 as normal. With * in printf(“%*d”,width,n);, because the order is * then d, width actually sets the output width of n, and n is what gets printed. For example: int n=3; scanf("%d",width); printf("%*d",width,n); When you type 2, it prints (空格)3

Maybe you’re asking what "*******"+2*(line>4? line-4:4-line) means?

If you look closely, it’s just a string pointer plus an int, in other words shifting the pointer. For example, when line=1 on the first row, 2*(line>4? line-4:4-line) comes out to 6, so the pointer to the 7-star string shifts by 6 and only one star gets printed. This is the shortest one-liner diamond I’ve ever seen. If you know a shorter one, tell me here.

Esc

Keyboard shortcuts

Ctrl K /
Search and commands
j k
Next or previous post in a list
Enter
Open the selected post
h l
Older or newer post (on a post)
g h
Go to the log
g a
Go to the archive
g t
Go to tags
g s
Go to stats
t
Switch light or dark theme
r
Random post
?
Show this help