Short coding technique

Some kind of tricks in C

August 14, 2018 - 1 minute read -
shortcoding c

Read integer

while(~scanf("%d",&x)){/* do something */}

Since scanf() returns EOF when end-of-file is reached while reading, this while-loop read one integer to x until it reaches end-of-file.

EOF usally defined as -1, and ~(-1) == 0.

So when scanf() reads EOF, which indicates end-of-file, that while-loop terminates.

Discard first line

gets(x); /* x must be pointer */

Loop [n-1, 0]

while(n--){/* do something */}
for(;n--;){/* do something */}