text:
Print the alphabet four times
The program must print the alphabet four times: first in the normal alphabetical order, second in the order of a qwerty keyboard, third in the order of a dvorak keyboard, and lastly in reverse alphabetical order. The output should resemble this:
abcdefghijklmnopqrstuvwxyz
qwertyuiopasdfghjklzxcvbnm
pyfgcrlaoeuidhtnsqjkxbmwvz
zyxwvutsrqponmlkjihgfedcba

The output is not case-sensitive, and you can add or omit newlines or spaces wherever you wish.
The catch: the program must be less than 104 characters, or, in other words, smaller than the length of the alphabet times four.
I will accept the answer with the shortest code, unless I see something really clever or interesting that I am more impressed with.
EDIT: I will accept the shortest answer on Wednesday, 4/27/2011.
EDIT2: And the winner is (as usual) Golfscript in 64 chars! Second place, which is behind by only three chars, is also in Golfscript, with 67 chars, followed by Bash in third place with 72 chars.
But there were a few others I wanted to mention, such as this one, which, depending on your definition, only used 52 "characters", and this one where he wrote it in a language he created.
There were a few people who broke an unwritten rule and did not qualify, but I will mention them just for their way of thinking without the box.

Consider using a bounty for an answer that impressed you. I think accepting an answer in a code-golf should always be the natural criterion (i.e. length).

I lost using Tcl: https://tio.run/##DcrJEYQgEADAP1FQ1iZiHJYPLhHlnuFMnrXfjcKuFQsC3Q5QSHfKuJDq0rd5Xut8iCkDltr6mCdJTWUcxYTIQH7nK7OLyr0jcVxaZMuCKkbe6CE9b@eu1UkOwGy8pllV@tvPba0/

PHP, 99 bytes
As ISO 8859-1:
<?=base64_encode("i·yø!9%z)ª»-ºü1Ë:°z»rº*)jÇ_ä<\½¹æ§'àr¹Z¡ë¢vg²¨äÅ¹°¿<òÇî¶Êê¦æHâÞuÆÚ");

To reproduce reliably,
printf '<?=base64_encode("' >| 4times.php
printf abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba | base64 -d >> 4times.php
printf '");' >> 4times.php

That's an interesting way to do it. All of the other ones are variations on the same idea, but this one is a little different.

I don't think this should count; the question is tagged "Kolmogorov complexity" and specifies "104 characters" which means we should be discriminating on what we consider a character. Otherwise I'll just define my own character encoding with a single character that maps to the ASCII for an entire program that solves the problem, and then decode that.

@Adrian Petrescu: that's easily solved by requiring that the encoding already exist at the time the challenge is posed.

@Lowjacker Sure, but that seems to be a pretty arbitrary way to resolve this.

@Adrian Petrescu: Go ahead.

@Adrian It is somewhat arbitrary, but it is similar in spirit to this answer on meta: http://meta.codegolf.stackexchange.com/questions/9/what-programming-language-should-we-consider-for-the-code-golf-solution/10#10

@Adrian, The advantage of unicode when using characters vs bytes has been acknowledged for a long time. In my opinion it doesn't make sense for the question to be tagged Kolmogorov while asking for characters. It should be counting bytes. It's up to the question asker to be careful about these terms.

Python 2, 97 characters
q="qwertyuiopasdfghjklzxcvbnm"
a="".join(sorted(q))
print a,q,"pyfgcrlaoeuidhtnsqjkxbmwvz",a[::-1]

Sorting QWERTY and converting back from list to string is shorter than the alphabet itself!*
Another option for generating the alphabet in fewer characters than the alphabet itself:
print map(chr,range(65,91))

Although this prints a Python list of characters.
There's not much to be done here in the way of data compression; jamming the letters into 5 bits only saves 39 characters, which isn't a lot if you then have to un-jam them (and you still have to represent the bytes literally); it looks like zlib (just as an example) saves fewer than 20 bytes; encoding the sequence as a list of deltas to the next letter still takes 5 bits for each delta, because the largest in this sequence is -22:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
 1, 1, 1, 1, 1, 1, 1, -9, 6, -18, 13, 2, 5, -4, -12, 6,
 1, -15, 18, -15, 2, 1, 2, 1, 14, -2, -21, 19, -20, 12,
 -1, 3, 9, -19, 1, -4, 15, -6, -11, 14, -10, 16, -12, -5,
 4, 12, -6, 5, -2, -7, 1, 13, -22, 11, 10, -1, 4, 0, -1,
 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]

* Although only slightly.

Python 3.5: q="qwertyuiopasdfghjklzxcvbnm";a=sorted(q);print(*a,q,"pyfgcrlaoeuidhtnsqjkxbmwvz",*a[::-1])

Ruby 1.9, 88 87 84 80
puts b=[*?a..?z],:qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz,b.reverse

Bash, 82
echo {a..z}
echo qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz
echo {z..a}

Python, 97 96 "characters"
Taking your use of the word "characters" liberally, here's some python that uses 16-bit unicode characters to encode 3 normal characters each.  The program is a total of 96 characters, 35 of which are the weirdest unicode characters I've ever seen.
for i in range(104):print chr((ord(u'ࠠᒃ⃦ⵉ��割廕��匓�เ᳅ⵉૹ�懬ࣅű傎ᱨ�⤰〷�弙劶��ⶍKᓇࡤ^A'[i/3])>>i%3*5&31)+97),

I'm not sure the unicode garbage will come though correctly, so here's a python program to generate the above python program:
#!/usr/bin/python
import codecs
f=codecs.open('alpha.py','w','utf-8')
f.write('#!/usr/bin/python\n')
f.write('# coding=utf-8\n')
f.write('for i in range(104):print chr((ord(u\"')
S='''abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcbaa'''
for i in xrange(0,104,3):
 n=32*32*(ord(S[i+2])-97)+32*(ord(S[i+1])-97)+ord(S[i+0])-97
 f.write(u'%c'%n)
f.write('"[i/3])>>i%3*5&31)+97),\n')

Golfscript, 64 chars
"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz".$2%\1$-1%

Note: also 64 bytes. Actually, playing with Unicode and base changes seems counterproductive because base is too long a keyword.

Bash, 72
echo {a..z} qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz {z..a}

EDIT: removed tr -d.
Credits: Alexander, Roger.

Rules allow you to omit |tr -d ' ', saving 10 characters and making this version a leader at the moment of writing :-)

@Alexander, Cool ;-) did not know that. Thanks to @Roger though for pointing me in the right direction.

I was trying to find a more elegant solution with some sort of polynomial with powers of primes and modulo (or in other words find a simple enough permutation function that works through that sequence)... but can't spend the sort of time required for such a solution, so I'll leave it at that. Plus it'd be pretty hard to express concisely.

Windows PowerShell, 89
Not particularly good, but at least shorter than the output string:
[char[]](65..90)
'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz'
[char[]](90..65))

Way shorter now that I saw that there is a relaxation on whitespace. And a little shorter still, if I ignore case which I'm allowed to.

You've got an extra ) there. Should be 88.

Golfscript, 76, 67 chars
123,97>+."qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"\-1%

changed ruby code to Ventero's Golfscript alphabet generation.

Use 123,97>+ to generate the initial alphabet.

Thanks Ventero, I indeed saw that in your other post the other day.

CI - 92 chars
'a(1p'z((,0(4d)(.$)<)$)(0c0c.1+2p$.)>)$)qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz

CI ("Compiler/Interpreter") is a simple stack-based language I created for the "Self-Interpreting Interpreter" challenge (link to answer).  I posted that answer about two hours before this challenge was posted.  It's no GolfScript (which I still haven't gotten around to learning), as my goal was to make the interpreter short.
This program must be passed to the ci interpreter through standard input.  The interpreter treats characters after a terminating ) as input to the program.  My language doesn't support string literals, so stdin is taking its place.

Python 2.7.X - 103 characters ironically...
a='abcdefghijklmnopqrstuvwxyz'
print a,'qwertyuiopasdfghjklzxcvbnm pyfgcrlaoeuidhtnsqjkxbmwvz',a[::-1]

As it turns out, generating the alphabet in python takes more characters than hard-coding it. As does importing the alphabet. Gotta love a readability-centered language sometimes.

You don't need the space between the QWERTY and DVORAK strings, it would be 1 character less.

true, but python automatically appends a space between each item in the comma-separated printing list, so the space is my personal sacrifice to the alter of readable output.

You could use the + instead of , and save that space.

C - 163 135  chars
This doesn't meet the requirements as it clocks in at over 104 characters, but it was fun to make. Maybe someone will have some suggestions.
main(i){char a[105];strcpy(&a[26],"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz");for(i=0;i<26;)a[i]=a[103-i]=i+++65;puts(a);}

This compiles on GCC 4.5.1 (others untested). Yay for omitting #includes, return types, and variable declarations! Hardcoding would've resulted in a shorter program, but that isn't any fun.
Whitespaced version:
main(i) {
    char a[105];
    strcpy(&a[26], "qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz");
    for(i=0;i<26;)
        a[i]=a[103-i]=i+++65;
    puts(a);
}

C - 124 122 lame
Here is the lame hardcoded version, and it still doesn't make the cut.
main(){puts("abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba");}

Use puts() instead printf in second case — 2 chars less.

And replace while with puts(a); in first case, dropping *p=a; — 138 chars instead of 163.

Awesome suggestions! I had totally forgotten about puts. Changed.

C — 133 chars
Shortened version from Casey:
main(i){char a[105];strcpy(a+26,"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz");for(i=0;i<26;)a[i]=a[103-i]=i+++65;puts(a);}

Whitespaced:
main(i) {
    char a[105];
    strcpy(a+26, "qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz");
    for(i=0;i<26;)
        a[i]=a[103-i]=i+++65;
    puts(a);
}

Transposed output
Here is a version that does transposed output, for fun. 134 chars.
main(i){char*a="qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz";for(i=0;i<26;i++,a++)printf("%c%c%c%c\n",i+65,*a,*(a+25),90-i);}

Whitespaced:
main(i){
  char*a="qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz";
  for(i=0;i<26;i++,a++)
    printf("%c%c%c%c\n",i+65,*a,*(a+25),90-i);
}

Prints:

AqmZ
BwpY
CeyX
DrfW
EtgV
FycU
GurT
HilS
IoaR
JpoQ
KaeP
LsuO
MdiN
NfdM
OghL
PhtK
QjnJ
RksI
SlqH
TzjG
UxkF
VcxE
WvbD
XbmC
YnwB
ZmvA

Still does not fit, of course.

by declaring i as global and putting strcpy(...) to the first block of the for loop you get 129. still too much though.

Lua — 111 characters
Beats C and C++! :-)
print'abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba'

"Clever" version in Lua
129 characters
q='qwertyuiopasdfghjklzxcvbnm'a={q:byte(1,-1)}table.sort(a)a=q.char(unpack(a))print(a,q,'pyfgcrlaoeuidhtnsqjkxbmwvz',a:reverse())

Whitespaced:
q='qwertyuiopasdfghjklzxcvbnm'
a={q:byte(1,-1)}
table.sort(a)
a=q.char(unpack(a))
print(a,q,'pyfgcrlaoeuidhtnsqjkxbmwvz',a:reverse())

J
x=:(97+/i.26){a.
x
261329910883437428257896643x A.x
247073478763191548160234722x A.x
(_1+/-i.26){x

My first experience with J. The idea is simply to use the canonical (lexicographic) number of the required permutation; unfortunately this takes more characters than hard-coding it. But if one could find some arithmetic expression (using powers and whatnot) yielding the magic numbers, it could be shortened.

261329910883437428257896643 has the prime factorization  7601991213987797292923318887 so there are no powers in this one.

Python, 90 unicode chars
#coding:u8
print u"扡摣晥桧橩汫湭灯牱瑳癵硷穹睱牥祴極灯獡晤桧歪穬捸扶浮祰杦牣慬敯極桤湴煳歪扸睭究祺睸當獴煲潰浮歬楪杨敦捤慢".encode("u16")[2:]

run at ideone - http://ideone.com/R2dlI or codepad - http://codepad.org/lp77NL9w

Actually, it only has 52 "characters".

Javascript 139 121
new:
q='qwertyuiopasdfghjklzxcvbnm'
a=q.split('').sort()
alert(a.join('')+q+'pyfgcrlaoeuidhtnsqjkxbmwvz'+a.reverse().join(''))

old:
a=[]
a[26]='qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz'
for(i=0;i<26;i++)a[i]=a[52-i]=String.fromCharCode(i+65)
alert(a.join(''))

You could also have 121 with:
alert((a=(q='qwertyuiopasdfghjklzxcvbnm').split('').sort()).join('')+q+'pyfgcrlaoeuidhtnsqjkxbmwvz'+a.reverse().join(''))

Vyxal j, 26 bytes
kak•ṅ«
ċ↓U→u°⟇Ȯ≤Ṙ]1biẊ«kzW

Try it Online!
-3 thanks to @A username

26 bytes

@Ausername nice, wrap stack reduces three irritating pairs

why the downvote on this answer?

Idk, maybe someone's grumpy.

25 bytes with all newlines omitted from output (not sure if that's valid): Try it Online!

@Wasif that downvote was me accidentally missing the upvote button and not noticing until I saw the -1 rep that comes with a downvote

Oh @lyxal sorry

PHP 88 bytes
<?=$a=join(range(a,z)),~Žˆš‹†Š–žŒ›™˜—•”“…‡œ‰‘’†™˜œ“žšŠ–›—‹‘ŒŽ•”‡’ˆ‰…,strrev($a);

J - 69 char
'pyfgcrlaoeuidhtnsqjkxbmwvz'(,~|.)&(,\:~)'mnbvcxzlkjhgfdsapoiuytrewq'

Explanation:

(,\:~) y - Sort y in descending order (\:~), and append (,) that to y.
x (,~|.) y - Reverse (|.) y, and append that to the front of x.
x F&G y - Execute (G y) F (G y), that is, perform F on the results of applying G to the arguments.

So, all together, we append the alphabet, backwards, to both the Dvorak and reverse-QWERTY strings, then reverse the QWERTY/alphabet one and put that in front of the Dvorak/alphabet one.

Bash, 64
I'm very late to the party, but I have a 64 character solution. Program needs to be saved to disk to work
echo {a..z} $(sed 1d $0|base64) {z..a};exit
««·+¢¢–¬uø!ŽIsÅËÛžjr~+•ªº'a¶{*ŽL[›ó

How it works:
{a..z} and {z..a} are pretty self explanatory, but basically that just prints every character in that respective range.
$(sed 1d $0|base64) outputs the program, ignores the first line, then passes it through a base64 encoder (as some other examples have done).
The reason this is shorter than other similar examples...
...is because the {a..z} ranges are shorter than base64 encodings, so I only need to base64 encode half the string. And because I'm reading the binary data from file rather than storing it in a string, I don't need to escape any character in code.
How to recreate this script:
If the code doesn't copy/paste correctly from Stack Exchange to your text editor then run the following in your command line (shell agnostic):
echo 'echo {a..z} $(sed 1d $0|base64) {z..a};exit' > alphabetgolf
echo 'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz' | base64 -d >> alphabetgolf

Then to run:
bash alphabetgolf

Deorst, 39 bytes
EfEuE|'pyfgcrlaoeuidhtnsqjkxbmwvz'EfVE;

Try it online!
How on Earth is Deorst beating everything bar Jelly???
How it works
Ef             - Push the lowercase alphabet
  EuE|         - Push 'qwerty…vbnm'
      '…'      - Push that string
         Ef    - Push the alphabet
           VE; - Reverse and concatenate

05AB1E, 25 bytes
AžW.•8t”a$äJÚ₁вƒüu¯Cê•AR»

Try it online!
Explanation
A                          # Push alphabet
 žW                        # Push qwerty string
   .•8t”a$äJÚ₁вƒüu¯Cê•     # Push compressed dvorak string
                      AR   # Push reversed alphabet
                         » # Join entire stack with newlines

C++
It's kind of sad when the shortest way to do something in a language is to hard-code it.
#include <iostream>

int main()
{
 std::cout<<"abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba";
}

You don't need to output the linefeeds.

@Low: Doh!  I forgot to remove those when I took out the line breaks I realized I didn't need.  Thanks for pointing that out.

This is a very obvious solution, and it surpasses the maximum length requirement.

std::cout is shorter that using namespace std, and you can skip void.

@Alex: Thanks for pointing that out.

You could put the {} and the code in one line.

J (77)
(,|.@(26&{.))(,~/:~@(26&{.))'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz'

Shaved off 3 characters by using a variable:
(,|.@a)(,~/:~@(a=.26&{.))'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz'

Shaved off 2 more characters by using a value-level approach:
(|.a),~t,~a=./:~26{.t=.'qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz'

Haskell (95)
main=putStr$['a'..'z']++"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"++['z','y'..'a']

Perl (51)
There's no rule that says I can't.
use LWP::Simple;print get("http://bit.ly/fGkflf");

See the list of standard loopholes.

Q (68)
.Q.a,"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz",(|:).Q.a

Outputs:
"abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfg
crlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba"

Tried to find an improvement on hard-coding the middle two but didn't come up with one.

K - 69 char
b,a,|b:a@<26#a:"qwertyuiopasdfghjklzxcvbnmpyfgcrlaeouidhtnsqjkxbmwvz"

Explanation:

26#a: - Assign the two keyboard layouts to a, and then take the first 26 characters.
b:a@< - Sort a and assign that to b: < provides the permutation for an ascending sort, and @ lets us index a in order to sort it.
b,a,| - Append in a row b, then a, then the reverse (|) of b.

Pyth, 57
G"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"VG

Alphabet, string, reversed alphabet. G is the alphabet. Print is implicit.

Dyalog APL, 60 bytes
⎕A'QWERTYUIOPASDFGHJKLZXCVBNMPYFGCRLAOEUIDHTNSQJKXBMWVZ',⌽⎕A

Prints:
  ABCDEFGHIJKLMNOPQRSTUVWXYZ  QWERTYUIOPASDFGHJKLZXCVBNMPYFGCRLAOEUIDHTNSQJKXBMWVZ ZYXWVUTSRQPONMLKJIHGFEDCBA

Which is permitted as per OP:

The output is not case-sensitive, and you can add or omit newlines or spaces wherever you wish.

Jelly, 36 bytes
Øa;Øq;“pyfgcrlaoeuidhtnsqjkxbmwvz”;U

Try it online!
Explanation:
Øa;Øq;“pyfgcrlaoeuidhtnsqjkxbmwvz”;U    |
Øa;                                     | alphabet
   Øq;                                  | list with all rows of the qwerty keyboard
      “pyfgcrlaoeuidhtnsqjkxbmwvz”;     | string
                                   U    | reverse

05AB1E, 60 59 bytes
AÂ"qwertyuiopasdfghjklzxcvbnm""pyfgcrlaoeuidhtnsqjkxbmwvz"»

Try it online!
AÂ - pushes the bifurcated alphabet.
"qwertyuiopasdfghjklzxcvbnm""pyfgcrlaoeuidhtnsqjkxbmwvz" - Pushes qwerty and drovak.
» - Prints stack.
05AB1E, 57 bytes (If you don't care about random \n)
AÂ"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"»

Try it online!

In the first example, you can save a byte by replacing "" with a newline.

05AB1E, 24 bytes
AžWDS•{2εFƵIƶsðÖz•.IJAR»

Try it online!

Scratch, 103 bytes (w/ Costume Names)
Try it Online!
It would be impossible to do within the constraints without costume or backdrop names, so this is what you get! The sprite has 5 costumes, whose names are  , abcdefghijklmnopqrstuvwxyz, qwertyuiopasdfghjklzxcvbnm, pyfgcrlaoeuidhtnsqjkxbmwvz, and zyxwvutsrqponmlkjihgfedcba. Being at the byte limit was a complete coincidence, but with such methods, it's as small as it can be! Alternatively, 7 blocks.
when gf clicked
delete all of[A v
switch costume to[ v
repeat(4
next costume
add(costume[name v])to[A v

Explanation
when gf clicked             Initiates code
delete all of[A v           Clears the list of alphabets
switch costume to[ v        Switches to the first costume
repeat(4                    Loops code for each alphabet
next costume                Changes the costume, and therefore the costume name
add(costume[name v])to[A v   Adds the name of the current costume to the list

Bash, 109
a(){ printf "$@";}
v=`a "\%o" {97..122}`
a $v
a qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz
a $v|rev

Output:
abcdefghijklmnopqrstuvwxyzqwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvzzyxwvutsrqponmlkjihgfedcba

Mouse-2002, 99 bytes
65i:(i.h.<^i.!'i.1+i:)"qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz"(i.64>^i.!'i.1-i:)

Self-explanatory.

RProgN, 62 Bytes Noncompeting
a S . "qwertyuiopasdfghjklzxcvbnmpyfgcrlaoeuidhtnsqjkxbmwvz" a

I'm a bit disappointed RProgN didn't exist at the time of this question. It could have won something!
Try it Online!

Scala, 128 Bytes
Not golfy enough, but readable :)
val l=("qwertyuiopasdfghjklzxcvbnm","pyfgcrlaoeuidhtnsqjkxbmwvz");List(l._1,l._1.sorted,l._2,l._2.sorted.reverse).mkString("\n")

Jelly, 25 bytes
Øa;Øq;“¡®×Ṫ}Æ¬#Q>Ẉṛ’œ?$;Ṛ

Try it online!

Subleq (8-bit word), 87 bytes,
4  52 6
52 -1 3
4 27 0
32 -1 12
4  9 15
4 30 9
52 -1 21
31  52 24
4  28 18
-25 -25 -1
-54 1
10
113 119 101 114 116 121 117 105 111 112  97 115 100
102 103 104 106 107 108  96 120  99 118  98 110 109 10
112 121 102 103  99 114 108  97 111 101 117 105 100
104 116 110 115 113 106 107 120  98 109 119 118 122 10

Subleq Emulator
Could shave 3 bytes off removing the line feeds but I like it better this way.
Explanation
  4  52  6   ' 0: 52: = 52: + 1 # 52: is the z in the qwerty string and is serving double duty
             '    as the output letter for the 1st and 4th lines
 52  -1  3   ' 3: output char(52:) # This line will output the 1st line
  4  27  0   ' 6: 27: = 27: + 1 if 27: <= 0 goto 0 # 27: is initialized to -25
 32  -1 12   ' 9: output char(32:) # the 32 will be incremented every time through the loop.
             '    This line will output the 2nd and 3rd lines
  4   9 15   '12: 9: = 9: + 1
  4  30  9   '15: 30: = 30: + 1 if 30: <= 0 goto 9 # 30: is initialized to -54
 52  -1 21   '18: Output char(52:) # This line will output the 4th line
 31  52 24   '21: 52: = 52: - 1
  4  28 18   '24: 28: = 28: + 1 if 28: <= 0 goto 18 # 28: is initialized to -25
-25 -25 -1   '27: When execution reaches this point this instruction will be 1 1 -1 which will exit
-54   1      '30: & 31: data for loops
 10          '32: to 86: data for the 2nd and 3rd lines
113 119 101 114 116 121 117 105 111 112  97 115 100
102 103 104 106 107 108  96 120  99 118  98 110 109 10
112 121 102 103  99 114 108  97 111 101 117 105 100
104 116 110 115 113 106 107 120  98 109 119 118 122 10


text:
'Add' up the letters in a word
My dad is a retired teacher, and he used to give combined spelling and math quizzes, where the student would spell a word, and then 'score' the word by adding up the letters, where a=1, b=2, etc. (e.g. cat = 3+1+20=24).  This made grading the quizzes easier, as he would just have to check for incorrect 'scores' rather than incorrectly spelled words, and had the added benefit of testing 2 skills at once.
He hired a friend of mine to write a program that would score words for him, so he could generate lengthy answer keys without error.  This problem is inspired by that program.
Requirements:

Accept any word with uppercase and lowercase letters
Return an error for any special characters, i.e. spaces, hyphens, @^%# etc.
a=1, b=2,... and A=1, B=2,...
Print the score of the word
(Optional) check that the word is in a dictionary after scoring, and print a warning if it is not.
No importing an external letter->number dictionary.  You must generate it yourself.

Any language is acceptable. This is similar to the 'digital root battle,' but much simpler.

Can a word contain numbers? Shall I throw an Exception or something similar if it contains numbers?

Is this supposed to be a code golf?

@Helper Method: A word containing a number should throw an exception or something similar

@Peter Taylor: Yes, how should I explicitly mark it as such?

@Zach Using the code-golf tag.

The warning message should be given in some way.

@Helper Method: what would you suggest?

Did your dad even bother teaching the "I before E except after C" rule?

Yeah, only checking scores? I'd spell cat as aaaaaaaaaaaaaaaaaaaaaaaa. Dad: Score is 24? That's right!

@ericw31415 Every hashing function has collisions ;-).  So far none of his students have tried that attack vector

@Zach Also, it would be too complex if his dad made his students do SHA-512 of their words.

@ericw31415 yes, but to do that you need to know how to spell cat.

Golfscript - 23 chars
0\{.31&.(.26%=@64///+}/

Ensure there are no trailing newlines in input (e.g. use echo -n).

We have a new winner!

Generally, external filtering is supposed to be included in character count somehow (Ctrl-f external filtering.), though I assume it's only 2 extra characters to do without.

@Jesse: echo -n really doesn't count as external filtering -- in fact the answer you linked suggests it as a valid form for input.

Ruby, 43 characters
$_=gets.upcase;p~/[^A-Z]/?_: $_.sum-64*~/$/

The error message this generates isn't exactly helpful, though.
Both solutions posted here assume the input has no trailing linebreak, so to test them, use echo -n.
Ruby, 76 characters with dictionary check
l=STDIN.gets;$_=l.upcase;p~/[^A-Z]/?_: $_.sum-64*~/$/;[*$<].index(l)||$><<?W

The warning message consists of the single character "W". The path to the dictionary has to be supplied via ARGV. Example usage:
$ echo -n asd | ruby addletters.rb /usr/share/dict/words
24
W
$ echo -n cat | ruby addletters.rb /usr/share/dict/words
24

You could chop of 9 characters in the dictionary check version by making the error message an exclamation mark.

You get a consolation prize for the shortest entry with a dictionary check.  Way to go!

Why was the dictionary check proposed if it doesn't give you any real edge (on the contrary, it just bloated the code)?

Python (65 64)
print sum(['',ord(i)-64]['@'<i<'[']for i in raw_input().upper())

This raises an error if the word contains non-letter characters, but not a helpful or informative one.  (Edit: tip of the hat to st0le for the indexing trick.)

print sum(['',ord(i)-64]['@'<i<'[']for i in raw_input().upper()) shaved a couple of chars.

Just one char actually. :-\

Save 4 characters by using input; forces user to put quotes around input strings, but "user-friendly" and "not dangerous" aren't in the spec!

Well, just change it to Python 3! raw_input→input

print sum([i,ord(i)-64]['@'<i<'[']for i in raw_input().upper())
another byte shaved

Python 2.6 (72 Chars) Without dictionary check
print sum(map(" abcdefghijklmnopqrstuvwxyz".index, raw_input().lower()))

Python 2.6 (178 Chars*) With dictionary check
w=raw_input().lower()
print sum(map(" abcdefghijklmnopqrstuvwxyz".index, w))
if w not in open('/usr/share/dict/american-english').read().split():
 print('Word not in dictionary')

*Can be lowered to 156 with a less helpful error message. :-)
Thanks to all commenters for helping improve this.

You might want to consider using the sum builtin with a generator expression, rather than a for loop.  It would let you trim off a few chars (~17).

@jloy: Thanks for pointing that out.

the parentheses on print can be eliminated

its seems you're using a just once, so use the literal itself..."0abc....z".index(i) will work equivalently.

The 0 in your scoring array is clever, but it also means that cat0 is accepted without error, which isn't right, I think.  Which is too bad, since it would allow you to pass map(a.index,w) to sum instead (substituting the literal for a as st0le suggests).

@jloy: The dictionary check version says that cat0 is not the dictionary.  Am I supposed to do more error checking then that?

The dictionary check version is good, the shorter version needs to throw some sort of error, though it looks like that's only spelled out in the comments to the original question.

@jloy: Hmm, you're right.  I think I have fixed that now.

Java + Google Guava libraries, 347 characters, with dictionary check
Unreadable 1 long string version :-)
import java.io.*;import com.google.common.base.*;import com.google.common.io.*;class C{public static void main(String[]a)throws Exception{int s=0;for(int c:a[0].toUpperCase().toCharArray()){assert(c>64&&c<91);s+=c-64;}String d=Files.toString(new File(a[1]),Charsets.UTF_8);if(StringUtils.containsIgnoreCase(d,a[0]))System.out.println("w");System.out.println(s);}}

Human-readable version (sort of :-))
import java.io.*;

import com.google.common.base.*;
import com.google.common.io.*;

class C {
    public static void main(String[] a) throws Exception {
        int s=0;

        for(int c : a[0].toUpperCase().toCharArray()) {
            System.out.println(c);
            assert(c > 64 && c < 91);
            s += c - 64;
        }

        String d = Files.toString(new File(a[1]), Charsets.UTF_8);

        if (d.contains(a[0])) System.out.println("w");

        System.out.println(s);
    }
}

The dictionary path is now passed in via a[1], for assertions to work you have to use the -eaflag (+3 more chars). As for the dictionary, the dict /usr/share/dict/words (should be available on most *nix systems) has been used.

So far you're the only one with a dictionary check, so +1

one line? this isn't particularily readable this way, though i guess it saves chars

I will add a more readable solution (and also a shorter one using Google Guava to reduce boilerplate code).

You just allow ascii, but use Charset.UTF-8?

Because the String UTF-8 is shorter than the other charsets :-).

Scala: 59 chars, 7 of them payload, no dict:
(0/:"Payload".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
67

No dictionary so far. Negative result means: Negative!
(0/:"Pay!wall?".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
-1915

Handles German Umlaute gracefully, by the way:
(0/:"Müllrößchen".map(c=>if(c.isLetter)(c-'A')%32 else-999))(_+_)
155

Wow, less chars than the Perl version (and still more readable).

I tried SHiNKiROUs and chinesis-Perl-solution, but they didn't work for me. Saved them as alpha.pl and started them by perl alpha.pl. Do they just handle Ascii? Well - at Perl is such an old beast ... :)

Perl and Unicode is a big mess. You probably have to run them as perl -M5.010 alpha.pl or something like that.

I heard that I need single quotes instead of double quotes on Linux, and this worked, thanks.

Python (80)
w=raw_input().lower()
s=0
for l in w:s+=range(97,123).index(ord(l))+1
print s

Python v2 (65 but char ` will get accepted)
print sum(map(range(96,123).index,map(ord,raw_input().lower())))

v3 (60 chars, @ will be accepted but not counted, thanks jloy)
print sum(map(range(64,91).index,map(ord,input().upper())))

HINT: THERE IS A WAY TO REMOVE ONE MORE CHAR FROM YOUR SOLUTIONS. :)

@jloy What a helpful 'hint'. ;)

Python 3, 95 chars with dictionary
d=input().lower()
print(d in open("d").read()and sum(['',ord(c)-96]['`'<c<'{']for c in d)or'f')

The dictionary has to be in a file called d.
Python 3, 61 without dictionary, but stolen idea
print(sum(['',ord(c)-96]['`'<c<'{']for c in input().lower()))

VB.NET, 84 82 73 71
Console.Write(Console.ReadLine.Sum(Function(c)Asc(Char.ToUpper(c))-64))

Edit: With validation is:
Dim r=Console.ReadLine
Console.Write(If(r.All(AddressOf Char.IsLetter),r.Sum(Function(c)Asc(Char.ToUpper(c))-64),"Invalid input."))

129 characters. In which case:
C#, 118
var r=Console.ReadLine();Console.Write(r.All(char.IsLetter)?r.Sum(c=>char.ToUpper(c)-64).ToString():"Invalid input.");

This doesn't validate the input.

Oops! Hold on a second...

I think you should provide complete programs. Your C# solution doesn’t compile; you need to place it in a Main method inside a class declaration, and count all the characters.

No, because that code doesn't do anything, and it's not fair to disadvantage users of object-oriented languages. This is valid C#/VB.NET anyways.

Perl (52) (48)
golfed even more thanks to Timwi
perl -lpe "($w=uc)=~/[^A-Z]/&¨$w=~s/./$_-=64-ord$&/ge"

You're missing the -e flag there.

You should at least include the p and l interpreter flags in your character count. See this discussion on meta.

syntax error at -e line 1, near "(=" Execution of -e aborted due to compilation errors. What am I doing wrong?

if you're running on unix, change double quotes to single ones

@Timwi: 'Accept any word with uppercase and lowercase letters' went to the wrong thread, sorry. I deleted it now. @chinese: Yes, thanks, with single quotes it's ok. As long as I restrict myself to ascii input. :)

You get a consolation prize for the shortest non-golfscript entry.

Improving slightly on John's answer: Python (90)
s=0
for i in raw_input().lower():
 s+=("abcdefghijklmnopqrstuvwxyz".index(i)+1)
print(s)

adding the dummy char in the string beginning is shorter...parentheses can be removed

Erlang, 104
a()->
a(string:to_lower(io:get_line([])),0).
a([_|[]],S)->
S;
a([C|R],S) when C<${, C>=$`->
a(R,S+C-$`).

Golfscript - 39 chars
n%~{.96>{96}{64}if-..26>\0<|{0/}*}%{+}*

The error it throws is not exactly the best, but hey, it aborts execution.

I don't know anything about golfscript, so I'm going to assume this meets the requirements and declare you the winner!

Whoops, you've been beat!  I guess 2 days isn't long enough to wait on a code golf question?

PYTHON 62 68* Characters
print sum(map(chr,range(65,91)).index(c)+1 for c in input().upper())

Requires user to input strings using quotes, and is not safe (input executes code), but, as I said in a comment to another post, "user-friendly" and "not a security risk" ain't in the spec!

* I forgot about print, dammit.

jloy's answer is still shorter, actually, because of the input/raw_input difference.

05AB1E, 15 bytes
lvAyk>})D0åi0ëO

Try it online! Returns 0 on error.
lvAyk>})D0åi0ëO  # full program
 v               # for y in...
                 # implicit input...
l                # lowercased...
    k            # push 0-based index of...
   y             # y...
    k            # in...
  A              # the lowercase alphabet...
    k            # or -1 if not found...
     >           # plus 1
      }          # end loop
           i     # if...
         0       # 0...
          å      # is in...
       )         # stack...
            0    # push 0
             ë   # else...
              O  # push sum...
        D        # of stack
                 # implicit output

Husk, 17 bytes
?osṁo%32c¹¨eŻ→¨Λ√

Try it online!
Returns 'error' for invalid input, score of word otherwise.
?              Λ√       # if every element is a letter
 os                     # return the string of
   ṁ    c¹              # the sum of all their ASCII values
    o%32                # MOD 32
          ¨eŻ→¨         # otherwise, return the compressed string
                        # "error"

If it's acceptable to return '0' as the 'error' for invalid input, we can have a 11 byte 10 byte 9 byte solution:
§&ṁ%32Πm√

Ruby 1.9, 69
w=gets.chop.upcase
w[/[^A-Z]/]&&fail
p w.bytes.inject(0){|s,b|s+b-64}

Does only handle ascii characters. I thought Ruby is from our century? :)

@user unknown: The spec doesn't say it has to. Doing it would be rather complicated...

Perl (71)
($a)=lc<>;$a=~/[^a-z]/i&¨$x+=ord$_ for split//,$a;die$x-96*length$a;

GolfScript, 50(53)
Gives an error on bad characters, but not a very good one (50 characters):
);[{""123,97>+91,65>+?}/].-1?0<{{26%1+}%{+}*}{@}if

Gives "E" on error instead (53 characters):
);[{""123,97>+91,65>+?}/].-1?0<{{26%1+}%{+}*}{;"E"}if

The alphabet-generating snippet 123,97>+ is stolen from Ventero .

J (55)
+/64-~-&32`]@.(<&97)`_:@.(<&65)`_:@.(>&122)"0,I.a.&e."0

This satisfies all the conditions except the dictionary one. As an error condition, it returns "infinity" (the underscore symbol in J) for words that contain anything but letters.

Haskell (127)
(raises an error on weird characters)
(also: the space between toUpper. and \x is needed otherwise it parses it as(toUpper) .\ (x))
import Char
main=getLine>>=putStrLn.show.sum.(map$(-65+).ord.toUpper. \x->if x`elem`['A'..'Z']++['a'..'z']then x else error"")

Haskell (70)
(does not raise an error, but 45% shorter)
import Char
main=getLine>>=putStrLn.show.sum.(map$(-65+).ord.toUpper)

C++ (111 107)
void main(){int a=0;s8*b=new s8[99];for(cin>>b;*b;)if(isalpha(*b))a+=tolower(*b++)-96;else return;cout<<a;}

The "set up"/etc:
#include <iostream>
#include <cstdio>
#include <cctype>

#ifdef _MSC_VER
    typedef __int8 s8;
#else
    typedef signed char s8;
#endif

"Undefined" behavior (It's more 'bad practice' than 'undefined', but oh well):

void main() That says it all.
I'm using new without delete.

Jelly, 10 9 bytes
ŒuØAiⱮoµS

Try it online!
Seemingly, it turns out a byte shorter to actually error than to return 0.
Œu           Uppercase the input,
    i        find the index (or 0 if not found)
     Ɱ       of each letter from the input
  ØA         in "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
      o      replace any 0 with the corresponding character of the input,
       µS    then take the sum.

Jelly errors if it attempts to add integers and strings together, and although two strings can be added together by +, this still errors in the case of a fully symbolic input because S is defined specifically as a reduce starting from zero.

Nice.  It'll be tough to better (or even match) 9-bytes...

JavaScript 1.8, 80 chars
Surprisingly readable!
alert(Array.reduce(prompt().toLowerCase(),function(a,b)a+b.charCodeAt(0)-96,0))

For use in Chrome I had to convert it a little: alert(prompt().toLowerCase().split("").reduce(function(a,b){return a+b.charCodeAt(0)-96},0)). I still like JavaScript solutions most :)

It doesn't return an error when you do invalid character???

APL (34)
+/{⍵∊⍳26:⍵}¨{64-⍨A-32×96<A←⎕UCS⍵}⍞

Gives either the score, or a VALUE ERROR if there are non-alphabetic characters in the input.
Explanation:

⍞: read a line of input
{...}: function applied to every character of input
A←⎕UCS⍵: store the ASCII value of the current character in A
A-32×96<A: make character uppercase: from A is subtracted 32 if 96<A (so, if it's uppercase), otherwise 0
64-⍨: subtract 64 from this, giving A=1, B=2 ...
¨: apply this function to every character:
⍵∊⍳26: if the character is between 1 and 26...
:⍵: then return ⍵ (and since there's no else clause there will be a VALUE ERROR if it's not between 1 and 26)
+/: sum all the values together (and this value is automatically outputted because it's the final result).

F# (no validation) 79 57 chars
let a w=w|>Seq.fold(fun a b->a+(int b)-65)0|>printfn"%i"

C, 98 bytes
 int a(char *s){int b=0;while(*s){if(!isalpha(*s))throw 1;b+=(toupper(*(s++))-64);}printf("%d",b);}

C# with validation: 108 chars (with 12 for error message):
var s=Console.ReadLine();Console.Write(s.All(Char.IsLetter)?s.Sum(x=>x&'_'-'@').ToString():"Invalid input");

C# without validation: 60 53 chars:
Console.Write(Console.ReadLine().Sum(x=>x&'_'-'@'));

In the second one without validation, you can reduce the characters even more by removing the s variable declaration and using Console.ReadLine() inline.

JavaScript, 60 bytes
s=>[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)

If the program must return an error on invalid inputs, then 80 bytes:
s=>/[^a-z]/i.test(s)?_:[...s.toUpperCase()].reduce((a,b)=>a+b.charCodeAt()-64,0)

If an input is invalid, then the console will say that _ is not defined (there must not already be a variable defined called _).

JavaScript, 68 Bytes
This can almost certainly be golfed more
w=>[...w.toLowerCase()].map(v=>v.charCodeAt()-96).reduce((a,b)=>a+b)

With dictionary check (Node.js & Unix Descendants only) 195 Bytes
Uses /usr/share/dict/words, and can definitely be shortened (see the warn message)
w=>(require("fs").readFile("/usr/share/dict/words",(e,t)=>!(t+"").split`
`.includes(w=w.toLowerCase())&&console.warn(w+" not found in dict")),[...w].map(v=>v.charCodeAt()-96).reduce((a,b)=>a+b))

For an error message, you do console.error(), not console.warn().

But the challenge said to warn (5. (Optional) check that the word is in a dictionary after scoring, and print a warning if it is not.) Don't mean to be pedantic, but the challenge specified a warning

@SpeedyNinja I think it still counts, that isn't really the point of the challenge...

@EᴀsᴛᴇʀʟʏIʀᴋ it is 1 character shorter ;)

@SpeedyNinja You're right, I misread.

Python 3, 58 55
print(sum(ord(x)%32for x in input()if x.isalpha()or z))

without dictionary or stolen idea but still unhelpful error ;)
thx @Eᴀsᴛᴇʀʟʏ
Test here.

I think you can save a byte by switching to python 2 and doing print<SPACE>sum(ord(......., removing the 2 parentheses around the expression.

@EᴀsᴛᴇʀʟʏIʀᴋ that is right but than the input has to be in parenthesis and I don't want to promote python 2 ;)

PYTHON 2 IS LIFE!! and also, I don't think that would require the input to be parenthesized?

@EᴀsᴛᴇʀʟʏIʀᴋ sry i meant quoted.
input() in python3 is raw_input() in python2

oh, I forgot. Hm.

JavaScript (V8), 51 bytes
w=>w.split``.reduce((a,l)=>a+parseInt(l,36)-9,0)||x

Surprised nobody's made this golf yet.
Explanation:
w =>                // Function with w as argument
w.split``           // Split w into an array of characters
.reduce((a,l)=>a+   // Take the sum of...
parseInt(l,36)-9    // The value of the letter in base 36, then subtract nine (gives the number of the letter)
,0)||x              // Error if it's NaN (there was a special character), because x is not defined

Does this error for input of "123"?

@DominicvanEssen No, but my understanding of the requirements was that only symbols/special characters had to be handled, not numbers. If numbers also need to be handled it would be 12 more bytes. (As far as I can tell, none of the other JS answers error if given symbols anyway)

Perl 5 -pF, 26 bytes
/\PL/||map$\+=037&ord,@F}{

Try it online!
Outputs nothing as its error condition

Forth, 48 bytes
0 -rot bounds [do] [i] c@ 32 xor 64 - + [loop] .
(takes arguments from the stack)
a version that reads from stdin:
0 pad pad pad stdin read-line 2drop bounds [do] [i] c@ 32 xor [if] 64  - + [loop] .
the second version, but commented:
0 pad \ used later
pad \ where to put the bytes
pad \ how many bytes (it's an address, so it's a big number, and forth doesn't have types)
stdin \ where to get the bytes
read-line \ get the bytes (also returns the number of bytes got)
2drop \ ignore IO errors
bounds \ turn an address and a length into a start and end address
[do] \ iterate over all the address in said range
[i] \ get the current address
c@ \ get the character at the current address
32 xor \ make it uppercase
64 - \ letter to number (eg a -> 1)
+ \ add number to total (this is what the 0 is for)
[loop] \ end loop
. \ print resulting number

This doesn't handle uppercase characters in the input correctly, but the fix actually saves a byte: Try it online!
That being said, this also doesn't appear to perform the required input validation. If validation is too clunky, feel free to keep a non-validating version as well, so long as you mark it as such.
Also I'm not entirely sure that that snippet is a valid submission, but you save two more bytes by making it a named function.

Vyxal, 9 bytes
ʀA[⁰øA∑|u

Try it Online!
Ties with jelly but pushes -1 if there is an error.
ʀA             # check if every character is in the alphabet
  [⁰øA∑        # if true, sum the character values of the input string
        |u     # else, return -1

You don't need the ⁰, implicit input will work.

also, you can get 7 bytes returning 0: øA∑?ʀA∧

i dont think returning 0 is okay here because an empty word scores 0

C, 97 Chars
int r(c*z){int x=0;while(*z){char w=tolower(*(z++));if(w<96|w>122)return-1;x+=w-96;}return x;}

It returns -1 if there's an invalid character.

K, 44
{$[=/x in\:a:.Q.a,.Q.A;+/(a!,/2#,1+!26)x;`]}

Returns ` for any non alphabetic input

VBA 120
Sub s(t)
For i=1 To Len(t)
a=Asc(Mid(t,i,1))-64
a=IIf(a>32,a-32,a)
If a<1 Or a>26 Then Print
b=b+a
Next
MsgBox b
End Sub

Print does not cause a compile-time error, though the syntax is invalid, which causes an exception to be thrown and the program to exit if, and only if, the character is not an upper- or lower-case letter.

Perl (42 31)
perl -F -pale '$c+=ord(uc$_)-64for@F;$_=$c'

I hope counting F, p, a and l as 1 character was correct.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Tips for golfing in C
What general tips do you have for golfing in C? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C (e.g. "remove comments" is not an answer). Please post one tip per answer. Also, please include if your tip applies to C89 and/or C99 and if it only works on certain compilers.

I think the biggest single-sentence hint is: Read the winning codes submitted to IOCCC.

Use bitwise XOR to check for inequality between integers:
if(a^b) instead of if(a!=b) saves 1 character.

a-b gives you the same effect.

Similarly you can use a*b instead of a&&b (has different precendence, may or may not be bad). If you know a /= -b (e.g. they are unsigned) then a||b == a+b

better yet combine it with the Elvis Operator ?: (instead of if) : for exemple to just do something if differents:  a^b?_diff_:;

@OlivierDulac Is there a compiler that accepts an empty ternary if false branch?

@OlivierDulac You can check. From what I know, GCC has a ?: operator which is just equivalent to a ? a : b

Abuse main's argument list to declare one or more integer variables:
main(a){for(;++a<28;)putchar(95+a);}

(answer to The alphabet in programming languages)
This solution also abuses the fact that a (a.k.a. argc) starts out as 1, provided the program is called with no arguments.
Use global variables to initialize things to zero:
t[52],i;main(c){for(;i<52;)(c=getchar())<11?i+=26:t[i+c-97]++;
for(i=27;--i&&t[i-1]==t[i+25];);puts(i?"false":"true");}

(answer to Anagram Code Golf!)

There are no data types defined for variables, no return type of main function. Is this valid C syntax?

@Pavitra : yes, this is commonly known as the "pre-ANSI" or "K&R" C variant. A variable without a type declared explicitly is an int. This has since been deprecated and all variables and functions are required to be declared with a type.

Avoid catastrophic function-argument type declarations
If you're declaring a function where all five arguments are ints, then life is good. you can simply write
f(a,b,c,d,e){

But suppose d needs to be a char, or even an int*. Then you're screwed! If one parameter is preceded by a type, all of them must be:
f(int a,int b,int c,int*d,int e){

But wait! There is a way around this disastrous explosion of useless characters. It goes like this:
f(a,b,c,d,e) int *d; {

This even saves on a standard main declaration if you need to use the command-line arguments:
main(c,v)char**v;{

is two bytes shorter than
main(int c,char**v){

I was surprised to discover this, as I have not so far encountered it on PPCG.

Why on Earth does that work??

Apparently this is called K&R style and it precedes ANSI C by a decade.

Note that using K&R features and newer (say '99) features together nay or may not be possible. Depends on your compiler.

@dmckee is right. C99 does not allow implicit int, so you have to use -std=gnu99 and now you're not portable. In clc-speak, you're not even writing "C" code per se, but "Gnu99-C". 'Round here we mostly ignore that, but it's good to mention it if you post code that is compiler-specific. Sometimes people actually do download and execute these programs of ours. :)

@luserdroog: You can use -std=c89 to tell gcc or clang to compile your code according to that older standard, which does allow implicit int with only a warning.

Quite often I've found that main(char*s,int**a) is the shortest declaration. s=*++a will still work as expected, as sizeof(int*) == sizeof(char*).

@primo In a conforming program, you are not allowed to change the type of the parameters of main(). You may rename them or use a typedef'd type, but you can't change them. main(char*s,int**a) is a wildly non-portable gcc extension. But on the other hand, K&R style parameters are just as non-portable and no longer standard C.

The comma operator can be used to execute multiple expressions in a single block while avoiding braces:
main(){

int i = 0;
int j = 1;
if(1)
    i=j,j+=1,printf("%d %d\n",i,j); // multiple statements are all executed
else
    printf("failed\n");

}

Outputs: 1 2

Doesn't work if one of the statements is break.

@MaxLawnboy because break is a statement, and this answer is talking about expressions.

Instead of >= and <= you can simply use integer division (/) when the compared values are above zero, which saves one character. For example:
putchar(c/32&&126/c?c:46); //Prints the character, but if it is unprintable print "."

Which is of course still shrinkable, using for example just > and ^ (a smart way to avoid writing && or || in some cases).
putchar(c>31^c>126?c:46);

The integer division trick is for example useful to decide whether a number is less than 100, as this saves a character:
a<100 vs 99/a

This is also good in cases when higher precedence is needed.

You can write putchar(c>31&c<127?c:46);

Certain compilers, such as GCC, allow you to omit basic #includes, param, and return types for main.
The following is a valid C89 and C99 program that compiles (with warnings) with GCC:
main(i) { printf("%d", i); }

Notice that the #include for stdio.h is missing, the return type for main is missing, and the type declaration for i is missing.

Technically it's not valid according to standards as main accepts zero or two parameters, not one. Not that anyone cares in code golf.

Calling printf() (or any variadic function) without a prototype causes undefined behaviour. GCC does not compile standard C by default. If you invoke gcc in C89 mode (gcc -ansi -pedantic) or C99 mode (gcc -std=c99 -pedantic), you will get quite a few complaints, at least in the latter case.

@NisseEngström: the calling conventions on mainstream C implementations make it safe to call variadic functions without prototypes.  So most C implementations do define the behaviour.

Use lambdas (unportable)
Instead of
f(int*a,int*b){return*a>*b?1:-1;}
...
qsort(a,b,4,f);

or (gcc only)
qsort(a,b,4,({int L(int*a,int*b){a=*a>*b?1:-1;}L;}));

or (clang with blocks support)
qsort_b(a,b,4,^(const void*a,const void*b){return*(int*)a>*(int*)b?1:-1;});

try something like
qsort(a,b,4,"\x8b\7+\6\xc3");

...where the string literal contains the machine language instructions of your "lambda" function (conforming to all platform ABI requirements).
This works in environments in which string constants are marked executable. By default this is true in Linux and OSX but not Windows.
One silly way to learn to write your own "lambda" functions is to write the function in C, compile it, inspect it with something like objdump -D and copy the corresponding hex code into a string. For example,
int f(int*a, int*b){return *a-*b;}

...when compiled with gcc -Os -c for a Linux x86_64 target generates something like
0:   8b 07                   mov    (%rdi),%eax
2:   2b 06                   sub    (%rsi),%eax
4:   c3                      retq

MD XF wrote a bash script that may assist in the writing of simple "lambda" functions.
Edit: This technique was previously published by Shinichiro Hamaji in this document.
GNU CC goto:
You can call these "lambda functions" directly but if the code you're calling doesn't take parameters and isn't going to return, you can use goto to save a few bytes. So instead of
((int(*)())L"ﻫ")();

or (if your environment doesn't have Arabic glyphs)
((int(*)())L"\xfeeb")();

Try
goto*&L"ﻫ";

or
goto*&L"\xfeeb";

In this example, eb fe is x86 machine language for something like for(;;); and is a simple example of something that doesn't take parameters and isn't going to return :-)
It turns out you can goto code that returns to a calling parent.
#include<stdio.h>
int f(int a){
 if(!a)return 1;
 goto*&L"\xc3c031"; // return 0;
 return 2; // never gets here
}
int main(){
 printf("f(0)=%d f(1)=%d\n",f(0),f(1));
}

The above example (might compile and run on Linux with gcc -O) is sensitive to the stack layout.
EDIT: Depending on your toolchain, you may have to use the -zexecstack (for gcc) or -Wl,-z,execstack (for clang) compile flag.
If it isn't immediately apparent, this answer was mainly written for the lols. I take no responsibility for better or worse golfing or adverse psychological outcomes from reading this.

I've just written a script to read parts of a C function from standard in and print a C lambda. Might be worth mentioning in your answer, might just be nice for you to see since you taught me to do this in the first place.

The ternary conditional operator ?: can often be used as a stand in for simple if--else statements at considerable savings.
Unlike the c++ equivalent the operator does not formally yield an lvalue, but some compilers (notably gcc) will let you get away with it, which is a nice bonus.

Addition: If you only need an if, but not an else then the ternary can still be useful.

&& and || can also be used: if(x==3)f() becomes with your suggestion x==3?f():0, and can be further improved to x==3&&f(). But be careful with operator precedence - if f() is replaced with y=1, then the && solution requires an extra set of parenthesis.

I'd never realized that gcc's ?: yields an lvalue.  Can I use that in production code?  lol

@ugoren: x==3&&f() can be further golfed to x^3||f()

@fgrieu, yes, though it's not exactly the topic here (this answer suggests it).

http://graphics.stanford.edu/~seander/bithacks.html
Bits are nice.
~-x = x - 1
-~x = x + 1

But with different precedences, and don't change x like ++ and --. Also you can use this in really specific cases: ~9 is shorter than -10.
if(!(x&y)) x | y == x ^ y == x + y
if(!(~x&y)) x ^ y == x - y

That's more esoteric, but I've had occassion to use it.
If you don't care about short-circuiting
x*y == x && y
if(x!=-y) x+y == x || y

Also:
if(x>0 && y>0) x/y == x>=y

The last tip ((x/y) == (x>=y)) is really useful.

Some of these don't work on my machine (I guess because these hacks largely rely on "undefined" behavior)

Define parameters instead of variables.
f(x){int y=x+1;...}
f(x,y){y=x+1;...}
You don't need to actually pass the second parameter.
Also, you can use operator precedence to save parenthesis.
For example, (x+y)*2 can become x+y<<1.

Or just x+y*2, saving yet another char.

@B1KMusic, x+y*2 isn't the same, due to operator precedence.

Right, lol. That would be x+(y*2). I was fixated on the x+y<<1 example, assuming it was being evaluated as x+(y<<1), and suggested the *2 instead. I didn't know bitshift operations were evaluated as e.g. (x+y)<<2

Use cursors instead of pointers. Snag the brk() at the beginning and use it as a base-pointer.
char*m=brk();

Then make a #define for memory access.
#define M [m]

M becomes a postfix * applied to integers. (The old a[x] == x[a] trick.)
But, there's more! Then you can have pointer args and returns in functions that are shorter than macros (especially if you abbreviate 'return'):
f(x){return x M;} //implicit ints, but they work like pointers
#define f(x) (x M)

To make a cursor from a pointer, you subtract the base-pointer, yielding a ptrdiff_t, which truncates into an int, losses is yer biz.
int p = sbrk(sizeof(whatever)) - m;
strcpy(m+p, "hello world");

This technique is used in my answer to Write an interpreter for the untyped lambda calculus.

The ternary operator ?: is unusual in that it has two separate pieces. Because of this, it provides a bit of a loophole to standard operator precedence rules. This can be useful for avoiding parentheses.
Take the following example:
if (t()) a = b, b = 0;  /* 15 chars */

The usual golfing approach is to replace the if with &&, but because of the low precedence of the comma operator, you need an extra pair of parentheses:
t() && (a = b, b = 0);  /* still 15 chars */

The middle section of the ternary operator doesn't need parentheses, though:
t() ? a = b, b = 0 : 0;  /* 14 chars */

Similar comments apply to array subscripts.

In this example, b-=a=b is even shorter. The ?: trick is still helpful, -= because also has low preference.

Good point; my example was needlessly complex.

Another point is that sometimes you want to flip the condition: for x>0||(y=3), x>0?0:(y=3) is useless, but x<1?y=3:0 does the job.

both clang and gcc allow for an empty true case in the ternary.  If omitted, its value is the value of the condition.  For example, x>5?:y=1

Any part of your code that repeats several times is a candidate for replacement with the pre-processor.
#define R return

is a very common use case if you code involves more than a couple of functions. Other longish keywords like while, double, switch, and case are also candidates; as well as anything that is idomatic in your code.
I generally reserve uppercase character for this purpose.

A shorter replacement would be -DR=return. Note that if you include certain characters, it may become necessary to have single or double quotes around the define -DP='puts("hello")'.

Since usually EOF == -1, use the bitwise NOT operator to check for EOF: while(~(c=getchar())) or while(c=getchar()+1) and modify value of c at every place

I don't know C well enough, but wouldn't while(1+c=getchar()) work?

@ɐɔıʇǝɥʇuʎs No. The addition operator + has higher precedence than the assignment operator =, so 1+c=getchar() is equivalent to (1+c)=getchar(), which does not compile because (1+c) is not an lvalue.

If you ever need to output a single newline character (\n), don't use putchar(10), use puts("").

Reverse Loops
If you can, try to replace
for(int i=0;i<n;i++){...}

with
for(int i=n;i--;){...}

for(;++i<n;){...} is even shorter if u declare i as a function parameter like fn(i)

Use for rather than while
Any while can be changed into a for of the same length:
while(*p++)
for(;*p++;)

On its own, that's not golf.  But we now have an opportunity to move an immediately-preceding statement into the parens, saving its terminating semicolon.  We might also be able to hoist an expression statement from the end of the loop; if the loop contained two statements, we could also save the braces:
a=5;while(*p++){if(p[a])--a;++b;}

for(a=5;*p++;++b)if(p[a])--a;

Even do...while loops should be replaced with for loops. for(;foo,bar,baz;); is shorter than do foo,bar;while(baz);.

The for loop allows up to two statements this way without braces, where the while loop only allows one. You could have avoided the braces in the first example with a comma as follows:
a=5;while(*p++)if(p[a])--a,++b;

If your program is reading or writing on one in each step basis always try to use read and write function instead of getchar() and putchar().
Example (Reverse stdin and place on stdout)
main(_){write(read(0,&_,1)&&main());}

Exercise:Use this technique to get a good score here.

What do you mean by in each step basis ?

Casey: I guess they mean if the program is reading something, operates on it, and writes output. In a streaming manner, so to say. As opposed to an approach where all the input has to be read and handled at once.

Joey is right, I meant the same,sorry I didn't checked my inbox until today.

That stack manipulation is gorgeous.

On what ABI and compiler does this work?  It does not work on x86-64 (GCC 8.3).

the last link is dead

Make use of return values to zero stuff. If you call some function, and that function returns zero under normal conditions, then you can place it in a location where zero is expected. Likewise if you know the function will return non-zero, with the addition of a bang. After all, you don't do proper error handling in a code golf in any case, right?
Examples:
close(fd);foo=0;   →  foo=close(fd);    /* saves two bytes */
putchar(c);bar=0;  →  bar=!putchar(c);  /* saves one byte  */

Abuse dark corners of array indexing

i[array] desugars into *(i+array), and since + is commutative for pointer+integer too, it is equivalent to *(array+i) and therefore array[i].
It's not very common to see an array indexing expression (whatever)[x] where whatever requires wrapping in parens and x doesn't, but when you see one, you can swap the two positions and write x[whatever] to save two bytes.
A real golfing example.

Another case where I've used this: I had a loop using pointer arithmetic to iterate over argv (named v for brevity), and I only needed the second character of each argv string. The original code used v[0][2] for this (the pointer arithmetic moved v so v[0] was always the current string). Indexing being higher precedence than dereferencing meant *v[2] wasn't an option (it would be (*v)[2], which saves nothing), but 2[*v] worked perfectly and saved two characters while behaving identically to v[0][2].

Use *a instead of a[0] for accessing the first element of an array.
Relational operators (!=, >,  etc.) give 0 or 1. Use this with arithmetic operators to give different offsets depending on whether the condition is true or false: a[1+2*(i<3)] would access a[1] if i >= 3 and a[3] otherwise.

a[i<3?3:1] is two characters shorter than a[1+2*(i<3)].

You may look into the IOCCC archives (international obfuscated C code contest).
One notable trick is to #define macros whose expansion has unbalanced braces/parentheses, like
#define P printf(

The mismatched parentheses have no value in themselves. The point is to define as much of the repeating pattern as possible. You might want to go further, with #define P;printf(.

How does this shorten byte count? Perhaps provide an example?

@Cyoce See for example this answer.

dprintf for conditional printing
As you may know, printing something by a condition can be done with ?:, && or ||:
cond&&printf("%d\n",n);
cond||printf("%d\n",n);
cond?:printf("%d\n",n);

Another interesting idea is to use dprintf, which is the same as printf except that it takes an extra argument, specifying the output file descriptor.  It will only output to STDOUT if said argument is equal to 1. This can be abused to potentially save a few bytes over the previously mentioned methods:
x-1||printf("%d\n",n);
dprintf(x,"%d\n",n);

Assign instead of return.
This is not really standard C, but works with every compiler and CPU that I know of:
int sqr(int a){return a*a;}

has the same effect as:
int sqr(int a){a*=a;}

Because the first argument is stored into the same CPU register as the return value.
Note: As noted in one comment, this is undefined behaviour and not guaranteed to work for every operation. And any compiler optimization will just skip over it.
X-Macros
Another useful feature: X-Macros can help you when you have a list of variables and you need to do some operation which involve all of them:
https://en.wikipedia.org/wiki/X_Macro

I quoted this and I was corrected, This is simply not true. It will only work with multiplications and divisions and when optimizations are turned off. This is because both operations happen to put their results in eax which is the common register for return. Parameters are stored either in the stack or ecx or edx. Try it yourself.

You are right, it's undefined behaviour, it also depends on the compiler and on the architecture, I usually check with gcc on x86 and armv7 before posting any answer using this trick. And of course if you enable optimization, any smart compiler would just delete the unnecessary multiplication.

I've seen this work with GCC but not others

@Gaspa79: gcc with -O0 always chooses to evaluate expressions in the return-value register.  I've looked at x86, ARM, and MIPS at least (on http://gcc.godbolt.org/), and gcc seems to go out of its way to do that at -O0.  But remember if you take advantage of this, the language you're programming in is gcc -O0, not C, and you should label your answer accordingly, not as C.  It fails at any optimization level other than -O0 debug mode, and doesn't work with clang IIRC.

I answered an SO Q&A about exactly why this works with gcc -O0, under what conditions: Return value in unused parameter when falling off the end of a non-void function (I didn't get into the GCC source code to look for that level of detail, but covered why assignment always "works": stores need the source value in a register, so GCC can't ever avoid evaluating into some register.  And it always picks the return-value register.)

Using asprintf() saves you the explicit allocating and also measuring the length of a string aka char*!
This isn't maybe too useful for code golfing, but eases the everyday work with a char arrays. There are some more good advises in 21st Century C.
Usage example:
#define _GNU_SOURCE
#include <stdio.h>

int main(int argc, char** argv) {
  char* foo;
  asprintf(&foo, "%s", argv[1]);
  printf("%s",foo);
}

for(int i=0;i<n;i++){a(i);b(i);}
can be made shorter a few ways:
for(int i=0;i<n;){a(i);b(i++);}
-1 for moving the ++ to the last i in the loop
for(int i=0;i<n;b(i++))a(i);
-3 more for moving all but one statement into the top and out of the main loop, removing the braces

Using the comma operator is another way to avoid braces in some cases.

Go functional!
If you can reduce your problem to simple functions with the same signature and defined as single expressions, then you can do better than #define r return and factor-out almost all of the boilerplate for defining a function.
#define D(f,...)f(x){return __VA_ARGS__;}
D(f,x+2)
D(g,4*x-4)
D(main,g(4))

Program result is its status value returned to the OS or controlling shell or IDE.
Using __VA_ARGS__ allows you to use the comma operator to introduce sequence points in these function-expressions. If this is not needed, the macro can be shorter.
#define D(f,b)f(x){return b;}

As an alternative to __VA_ARGS__, there's the following GNU extension: D(f,b...)f(x){return b;}

use scanf("%*d "); to read the dummy input. (in case that input is meaningless in further program)
it is shorter than scanf("%d",&t); where you also need to declare the variable t.
storing characters in int array is much better than character array. example.
s[],t;main(c){for(scanf("%*d ");~(c=getchar());s[t++]=c)putchar(s[t]);}

Actually, I use %*d not only in Golf because it's also useful in situations where one would, for example, want to skip a newline in scanf("%[^\n]%*c",str); :)

Print a character then carriage return, instead of:
printf("%c\n",c);

or
putchar(c);putchar('\n'); // or its ascii value, whatever!

simply, declare c as an int and:
puts(&c);

It is probably worth pointing out that this depends on a little-endian architecture. If c is a big-endian int, then you'll just get the carriage return. (On the other hand, if c is a char, you might get random garbage after instead of a carriage return.)

@breadbox yep, you are totally right; I just edited: the last excerpt should use c as an int (which is frequently easy to declare as such).

Does puts(&c) really work? That wouldn't necessarily be null-terminated.

@EsolangingFruit On little-endian with 32-bit ints, an int 0 ≤ c < 256 is stored as the byte sequence c 0 0 0. When interpreter the address of c as char *, we see a singleton string: the character c, followed by a null byte.

Missing includes and return values
As noted in the very first answer, some compilers (notably, GCC anc clang) let you get away with omitting #includes for standard library functions.
While that usually goes well, it might cause problems in some cases, since the implicit declarations of standard library functions inside the source code will cause the compiler to treat return values as ints. For example, the code
char*p=getenv("PATH");

wont work as expected on a 64-bit platform since getenv returns a 64-bit memory address which doesn't fit into an int.
In this case, there are at least three ways to use getenv without errors.

Include the header file as follows.
#include<stdlib.h>
char*p=getenv("PATH");

This is the right way™, but not very golfy; it costs 19 bytes.
Declare getenv with the pointer as follows.
char*getenv(),*p=getenv("PATH");

This costs 10 bytes.
Finally, unless your code wouldn't work on 32-bit platforms, compile your code on one of those or with the -m32 flag (gcc). This costs 0 bytes.

Swap variables
If you ever need to swap variables, don't use the pattern with an extra variable or that addition-subtraction-method, just do some chained XORing:
a^=b^=a^=b;

This is undefined behavior, due to a lack of sequence points in between two modifications of the same object. See here: https://stackoverflow.com/questions/9958514/sequence-point-xor-swap-on-array-get-wrong-result

This is incredible. 10+ years of coding C and I've always wondered if there was a way to do this, what a delight to stumble upon tonight

Try cpow() instead of cos()
Instead of
double y=cos(M_PI*2*x);

try something like
double y=cpow(-1,x*2);

This uses Euler's formula, a little complex analysis and the observation that assigning a complex to a double yields the real part (careful with variadic function calls and other subtleties).
\$\cos 2\pi x+j\sin 2\pi x=e^{j2\pi x}=e^{j\pi 2x}=\left(-1\right)^{2x}\$
This type of trick can be used to reduce
double y=cpow(-1,x/2);

into
double y=cpow(1i,x);

because \$\left(-1\right)^\frac{x}{2}=j^\frac{2x}{2}=j^x\$
Edit: Equations now inline \$\LaTeX\$ instead of images.

Exploit ASLR
On systems with ASLR (Address Space Layout Randomization), the address of a stack variable can be used as a one time pseudorandom number. Instead of something like...
srand(time(0));

...try something like
srand(&x)

...where the address of x (hopefully on the stack) is unique each time the program is run.

Hmm... Where have I seen this before? :) +1

Abuse two's complement
A lot of expressions can be changed by (ab)using two's complement. Take this for example:
getchar()+1

If you need higher precedence, you can use this:
-~getchar()

Or, if you're using it as the condition for a loop, this can be used:
~getchar()

Additionally, instead of subtracting one after another subtraction:
a+b-1

you can add the bitwise-NOT of the second operand:
a+~b

This applies similarly to multiplication by 2:
2*(a-b)-1

can be shortened to:
a-b+a+~b

@ceilingcat oh, yeah. That explains why it didn't work in my head. But I wonder why it worked in the ASCII rocket challenge.

import if you have to
As noted in the very first answer, some compilers (notably, GCC and clang) let you get away with omitting #includes for standard library functions.
Even if you can't just remove the #include, there might be other ways to avoid it, but that's not always practical or particularly golfy.
In the remaining cases, you can use #import<header file> instead of #include<header file> to save a byte. This is a GNU extension and it is considered deprecated, but it works at least in gcc 4.8, gcc 5.1, and clang 3.7.

instead of the printf loop
for(i=1;i<12;i++){if(!i%3)printf("\n");printf("%d",i);}

just use
for(i=1;i<12;i++) printf("%c%d",!(i%3)*10,i);

it helps me so much .

@SamHocevar 's answer (shorter by 2bytes)
for(i=1;i<12;i++) printf("\n%d"+!!(i%3),i);

Credits to @AbhayAravinda for ripping off three more bytes
for(i=1;i++<12;) printf("\n%d"+!!(i%3),i);

The incrementer here works as a part of the inspector.

The second line is incorrect; it will actually print the null characters.

lol im not pinting them into char array , it is terminal console, and nul character doesnt mean space nor a newline:/

You can use this: printf("\n%d"+!!(i%3),i); which is 2 characters shorter.

knock off 3 more bytes by changing for to for(i=1;i++<12;)

Hey sorry. It removes 3 bytes but adds 2. So effectively removes 1 byte

@NoShady420: That changes behavior, as the value of i used in both locations in the printf will be one higher. You could tweak the initialization/bounds to fix, or you could rely on implementation defined behavior by putting the ++ later for(i=1;i<12;) printf("\n%d"+!!(i++%3),i); (this assumes compiler evaluates arguments from right-to-left, and side-effects apply immediately, which is common, put it on the second use of i if it's left-to-right argument evaluation order.

Here are a few tips I've used to my advantage. I've shamelessly stolen them from others, so credit to anyone but me:
Combine assignment with function calls
Instead of this:
r = /* Some random expression */
printf("%d", r);

Do this:
printf("%d", r = /* Some random expression */);

Initialize multiple variables together (when possible)
Instead of this:
for(i=0,j=0;...;...){ /* ... */ }

Do this:
for(i=j=0;...;...){ /* ... */ }

Collapse zero/nonzero values
This is a neat trick I picked up from someone here (don't remember who, sorry). When you have an integer value and you need to collapse it to either 1 or 0, you can use !! to do so easily. This is sometimes advantageous for other alternatives like ?:.
Take this situation:
n=2*n+isupper(s[j])?1:0; /* 24 */

You could instead do this:
n=n*2+!!isupper(s[j]); /* 22 */

Another example:
r=R+(memcmp(b+6,"---",3)?R:0); /* 30 */

Could be rewritten as:
r=R+R*!!memcmp(b+6,"---",3)); /* 29 */

maybe R*-~!!mxxxx

Overload functions (unportable)
Instead of declaring multiple functions...
d(x){return x*2;}
float r(float x){return 1/sqrt(x);}
...
printf( "%d %f\n", d(2), r(2) );

...declare one "function" that does different things depending on return and parameter types.
(*f)()=L"\xf33f048d\xc3c0520f"; // global
...
printf( "%d %f\n", f(2), ((float(*)(float))f)(2) );

Try it online! This works because some ABI's (Linux x86_64, in this example) use separate registers for floating point and integer arguments and return values.
The disassembly of the (*f)() "function"...
0:       8d 04 3f                lea    (%rdi,%rdi,1),%eax
3:       f3 0f 52 c0             rsqrtss %xmm0,%xmm0
7:       c3                      retq

On a x86_64 Linux machine, this function  takes the first integer parameter, doubles it and places the result in %eax (char/short/int/long return value). It takes the first floating point parameter, computes a low precision reciprocal square root and places it in %xmm0 (float/double return value).

This would be a better answer if you decoded the x86 asm in a comment or something, and also link to a method for turning hand-written asm into strings.  I don't want to go look up an opcode table.  I can see it ends with a c3 RET (x86 being little-endian), but I can only guess that the other bytes are lea eax, [rdi+rdi] and rsqrtps xmm0,xmm0 (with no Newton iteration?  that's very inaccurate...), because that's what would make sense.

You can save 1 byte by using rsqrtps instead of ss.  The default FP environment has FP exceptions masked, so whatever happens in the high elements won't screw up the scalar value in the low element.

Inline arrays
If you need a non-int constant array and just use it once, you can do
float f(a){return (float[]){.3,.2,.7}[a];}

instead of
float z[]={.3,.2,.7};float f(a){return z[a];}

to save 3 bytes.
(In this case it can save one more byte since the blank after return can be omitted.)

Inverse flag update
Sometimes a challenge asks to determine a data set's specific boolean property. To avoid the unacceptably long return keyword, I often use a flag variable which gets updated in a loop and assign-returned at the end (I will refer to this tip for more detail on assign-returning).
When working with such boolean flags and boolean values, to update them I often use either f&=a|b or f*=a|b to align them with the result of a|b. This is equivalent to saying f = f && (a|b).
However, sometimes a flag needs to be inversely updated, meaning f = f && !(a|b). Naively, one would use f&=!(a|b) (9 bytes), or -- using fundamental logical equivalences -- one would golf it to f&=!a&!b (8 bytes).
For the case of an inverse flag update, though, one might be better off using the binary shift right operator >>, as the previous assignment is (when working with boolean values) equivalent to f>>=!(!a&!b), which simply golfs to f>>=a|b (7 bytes).
If the flag update in question does not involve parentheses due to negation (as in the previous example), inverse flag updating may still be shorter, as for example f&=!a|!b (8 bytes) is equivalent to f&=!(a&b) (9 bytes), which is equivalent to f>>=a&b (7 bytes).
Inverse flag updating may in certain cases also be used even though the values in question are not boolean (either 0 or 1).
If only one operand is boolean, bitwise and (&) can still be used, as the second operand's bits will all be cleared. When using bitwise or (|) or both operands are non-boolean, one should consider using logical and (&&) and logical or (||) to get a boolean result, even though they are one byte longer.
As a side node, these rules also apply when the expression is side-effect-dependent, meaning !f()&&!g() is equivalent to !(f()||g()) regarding the execution of g(), such that even in those cases inverse flag updating can be used.
For testing purposes, I wrote a simple truth table tester (TIO-link).
One recent real-world example of this technique in action would be for example my answer to Detect Rectangular Text.

Boolean constant string selection when the selector's true value is guaranteed to be one larger than the second option's length
At its heart, this tip attempts to golf a ternary if of the form cnd?str_true:string_false when two conditions are met, namely that both str_true and string_false are constant strings and cnd is either 0 or strlen(string_false)+1.
If the above conditions are met, the expression cnd?"true":"false" can be golfed* by one byte to "false\0true"+cnd (here cnd == 0 || cnd == 6 always holds); another byte can be shaved off by not escaping the null byte (a compiler dependent feature).
The tip in action
For this example, suppose the string selection's criterion is k%3's truthiness, where k-1 is never divisible by three. In this case the ternary if
k%3?"°@°":"_" // 13 bytes

can be golfed to:
"_\0°@°"+k%3 // 12 bytes

Which can be golfed down to eleven bytes if one does not escape the null byte.
Application in obfuscation
As the above requirements are rather strict, this tip is most likely not widely applicable. Nonetheless, the shown technique can also be used to potentially obfuscate a program at no further byte cost.
Given e as a truly boolean expression -- (e) == 0 || (e) == 1 holds -- with the proper operator precedence regarding the upcoming factor, the following snippets are interchangeable* at the same byte count -- when not escaping the null byte.
e?"lifeless":"lychee"
"lychee\0lifeless"+e*7

Bare in mind that this obfuscation is only non-detrimental to the byte count if the second option's string is not longer than eight characters -- since else the factor spans more than one byte.
*: If interpreted as constant strings.

If the strings to be selected are two or fewer octets in length, you can use wide characters. L"AB"+p will return "A" if p==0 and "B" if p==1.

Get the length of a string with puts() instead of strlen()
According to the standard C specification, puts() returns a non-negative integer on success. In practice, most C libraries seem to treat puts(s) as equivalent to printf("%s\n", s), which returns an integer equal to the number of bytes written.
As a result, the return value of puts(s) is equal to 1 + strlen(s). If the additional console output can be ignored, this saves a few bytes.

"a few" in this case is 4.

Calculating \$\lceil\log_{10}(n)\rceil\$
Especially in challenges where properties of decimal representations are of interest, one needs to find a number's decimal representation's length, or for \$n\in\mathbb{N}^+\$ equivalently, \$\lceil\log_{10}(n)\rceil\$.
In this post, several approaches are presented and discussed.
For a C source file containing approaches (a.1) to (b.3) together with a testing setup, see TIO.
I wrote this tip based on this answer of mine, searching for a smaller approach than (a.1).
If you know of any other approach possibly shorter in even a specific scenario, feel free to either add your own tip add to the list below.
(a.1) An expression in n, 20 bytes
snprintf(0,0,"%d",n)

Versatility is a great property of the above approach, when used to determine a number's decimal representation's length, the most direct approach might be the most byte-effective.
0 is given its correct decimal representation length of 1.
GCC only throws a warning for ignoring #include <stdio.h>, otherwise the inclusion would be very byte-heavy at potentially 19+20=39 bytes. If instead of sprintf(0, one uses sprintf(NULL, the byte count is increased to 23 bytes. If using both, the byte count could jump to 42 bytes.
(a.2) A function in n, 29 bytes
a(n){n=snprintf(0,0,"%d",n);}

By being a function, this approach's versatility is high; (a.1)'s compiler-specifics also apply, when properly returning, the byte count increases to 5+29=34 bytes.
0 is given its correct decimal representation length of 1.
(b.1) A function in n, requiring another variable, 32 bytes
b(n,k){for(k=0;n;k++)n/=10;n=k;}

Of all approaches presented, this one has the worst byte count. However, considering potential compiler restrictions discussed in (a.1), it could prove more byte-efficient, since the approach is nearer to the C core.
0 is given its incorrect decimal representation length of 0. One can make the case for defining \$\lceil-\infty\rceil:=0\$ which would make this approach closer to a logarithm implementation, when further defining \$\log(0):=-\infty\$.
Modification to calculate \$\lceil\log_b(n)\rceil\$ for a base \$b\in\mathbb{N}^+\$ is possible, changing the byte count by the bytes required to represent \$b\$ in C-source.
(b.2) A statement requiring existence of two variables, setting n=0, 20 bytes
for(k=0;n;k++)n/=10;

If another variable is already declared and n can be either discarded or needs to be cleared regardless and the use case is a whole block instead of a one-line expression, the above could be used. Since it is equivalent in byte count to (a.1), the behavioural differences have to be analyzed.
Minimally wrapped inside a function, it becomes (b.1), both being similar in features.
(b.3) A statement working additively on k, setting n=0, 17 (pot. 16) bytes
for(;n;k++)n/=10;

Another variation on (b.1), removing initialization of k. Furthermore, for(; leaves space for an expression, potentially allowing to save a semicolon's byte, effectively rendering this approach 16 bytes long.
(c.1) A statement in n, producing stdout-output, 14 bytes
printf("%d",n)

Courtesy of H.PWiz.
This approach's utter conciseness and simplicity may be alluring, its major drawback, however, is its stdout-output; tolerability being heavily challenge-dependent.
(c.2) A statement in n, producing stderr-output, 17 bytes
dprintf(2,"%d",n)

Courtesy of Jo King.
The above is equivalent to the five bytes longer fprintf(stderr,"%d",n) and a variant of (c.1), side-effecting not stdout but rather the much more clutterable stderr.
Ref. man dprintf.3

Use bitwise operators to convert characters to uppercase/lowercase. Bitwise AND with 95 (or '_') to convert to uppercase, bitwise OR with 32 (or ' ') to convert to lowercase, and to invert case, bitwise XOR with 32 (or ' ').
This only works for letters, and it also seems to work for just a few other characters: { and } are lowercase for [ and ], ~ and ` are lowercase for ^ and @, ) is lowercase for a tab, and * is lowercase for a newline.
Example.

Knowing basic logical equalities might be able to save a couple bytes. For instance, instead of if (!(a&&b)){} try instead using DeMorgan's law if (!a||!b){}. The same applies to bitwise functions: instead of ~(a|b) do ~a&~b.

Cf. De Morgan's laws.

Use s[i] instead of i<strlen(s) in string-handling loops
For example:
for(i=0;i<strlen(s);i++)s[i]=s[i+1];

can be shortened to:
for(i=0;s[i];i++)s[i]=s[i+1];

Though in this case one would most likely not bother with indices and use pointer incrementation; for(;*s;)*s=*++s;.

When your algorithm produces output in reverse order, take a pointer to the end of a buffer and write it in decreasing order, returning a pointer to the first element.  It's up to the caller to supply a buffer large enough for any this input, or for any possible input.
Base conversion / int-to-string is a classic example where this interface is used in real life, such as glibc's internal _itoa, used by the printf family of functions as well as some other internal callers.  The max buffer size is 65 bytes for a 64-bit integer -> base 2 string.
// takes a pointer to one-past-the-end, which is also a valid option.
char *itoa_end(unsigned long val, char *p_end) {
  // does *not* zero terminate the buffer.  Use *--p_end = 0;
  const unsigned base = 10;
  char *p = p_end;
  do {
    *--p = (val % base) + '0';
    val /= base;
  } while(val);                  // runs at least once to print '0' for val=0.

  // write(1, p,  p_end-p);
  return p;  // let the caller know where the leading digit is
}

For golfing, it can be more compact to take the pointer by reference and modify it, instead of returning it.  (return is a long keyword, and code depending on gcc -O0 evaluating expressions in the return-value register isn't even C.)
For example, I used this in ASCII art uncompression from a base-n number (i.e. int->string with a digit lookup table), where I already needed a char* arg, so it was very cheap to declare another as a char **.
Use *p everywhere you have p in the simple version.  *--*p decrements the caller's pointer, then dereferences that to reference the actual character.
/* int n = the number
 * int B = size of I = base
 * char I[] = input table
 * char **O = input/output arg passed by ref:
 *    on entry: pointer to the last byte of output buffer.
 *    on exit:  pointer to the first byte of the 0-terminated string in output buffer
 */
void semi_golfed_g(n,I,B,O)char*I,**O;
{
    for(**O=0 ; n ; n/=B)
        *--*O = I[n%B];
}

Set an array of int to the same value (C99, Linux, BSD, OSX)
Instead of
int a[n]=...,x=...;
for(int i=n;i--;)a[i]=x

Try something like
int a[n]=...,x=...;
wmemset(a,x,n);

On MSVC on Windows, wmemset() works on arrays of short instead of int.

Iirc wchar_t is 32 bits wide with gcc on Windows as well, unless you specify the -fshort-wchar flag.

Abuse wchar_t to print one character from a string
In a little-endian architecture, you can replace
putchar("string"[i])

with
printf(L"string"+i)

to save a byte.

With puts being even shorter replacement for printf if adding a newline is okay/desired.

Use bitwise and (&) when comparing boolean expressions to save one byte.
Example:
if(i^2&k/3) DoSomething;

Really, really useful when combined with the other tips

The example if(i^2&k/3) seems like it would be equivalent to if(i != 2 && k >= 3), but it's not because & has higher precedence than ^. Also, even if(i-2&k/3) wouldn't work, because a bitwise and of two nonzero values could result in zero. On the other hand, if(i!=2&k>2) would work.

Whenever a certain function is called several times, it's common to #define it to something shorter. However, certain compilers (MinGW and clang as far as I know) allows for something even more compact by using function pointers:
(*P)()=printf;
P("Test: %d\n", 10);

Other compilers might require an #include of the proper header file for it to work.

Favor recursion over loops, especially if going forwards then backwards
Loops, 67 bytes
l;f(char*s){for(l=0;s[l];)putchar(s[l++]);for(;l;)putchar(s[--l]);}

Try it online!
Recursion, 47 bytes
f(char*s){*s?putchar(*s),f(s+1),putchar(*s):0;}

Try it online!
You can remove two for-loops and a counter variable. Even if you use just one for-loop in order to loop in one direction, you could save ~10 bytes with this transformation.

Sometimes you can use floating point where you don't expect to.
Ignoring possible floating point imprecision issues you still can use them with many operators you wouldn't normally expect :

++ -- increment / decrement
! || && Boolean comparative
? and even ternary!

For scanning a string into an array, you can use
gets(str);

instead of
scanf("%s",str);

Yeah, except you should never use gets.

@MDXF Welcome to code golf

@MDXF: ... for the exact same reason you should never use "%s" instead of "%256s" as your scanf format string.  (Or whatever the buffer size is.)

Bonus points if the buffer is smaller than the input and the code relies on overflowing it.

When you have to walk a string you can walk the pointer instead of incrementing the index.
Code :
#include <stdio.h>

// print each char
void f(char* s) {
    for (int i=0;s[i];i++) putchar(s[i]);
}

// same output than f;
void g(char* s)
{
    for (;*s;) putchar(*s++);
}

int main(void) {
    f("hello\n");
    g("hello\n");
    return 0;
}

example: Remove duplicated & switched case

Use #define instead of functions when possible
For example:
f(int i,char*s){/*do something with i and s*/;}

Using #define can eliminate the argument list type, curly-braces and closing semicolon:
#define f(i,s)/*do something with i and s*/

Use bitwise operators for boolean conditions
For example:
if(a||b) /* do something */

This saves one byte:
if(a|b) /* do something */

Respectively, a!=b becomes a^b and a&&b becomes a&b
An example of using this trick.
Note that sometimes you have to use ||. For example:
if(!a)b++

can be written as
a||b++

but
a|b++

doesn't work.

It's not always true.
For example if I have this if:
if(!a)b++;
I can write: a||b++. And in this case, a|b++ doesn't work

This trick works in most C-like languages

Sometimes, albeit rarely, if your code contains many for loops, #define F for( may save a byte or two (especially if some of the loops have an empty init section).
If it is applicable to your situation, #define F;for( may save even more bytes.
Examples:
https://codegolf.stackexchange.com/a/153117/61405
https://codegolf.stackexchange.com/a/149629/61405

Use recursion over loops.
Recursive example
f(){printf("infiniteloop");f();}

For loop equivalent is 3 bytes longer.
f(){for(;;)printf("infiniteloop");}

I think you are missing a semicolon in your recursive example.

Do you have an example for a terminating program which could be golfed in this way? Or does this tip only apply to infinite loops?

Yes, I actually have the shortest c solution in this example

f(){f(printf("infiniteloop"));} would save a further byte in this example. Try it online!

Conditional printf different format
x>0?printf("%c",x):printf("%d",-x);
printf(x>0?"%c":"%.f",x,0.-x);     // float goes different registers

Used here

from the manual: If the precision is given as just '.', the precision is taken to be zero.

Use strings as arrays
Suppose you had an array like the following.
c[]={1,2,3,4,5,6,7,8,9,10};
// ...some code here...
printf("%d",c[i]);

You can make this at least 9 bytes shorter using this method.
char*x,*c="abcdefghij"; // initialize like this if you already have a 'char *' declaration somewhere.
c[]=L"abcdefghij";      // initialize like this you do not (thanks to @ceilingcat for teaching me this one).
// ...some code here...
printf("%d",c[i]-97);

You can also do something similar with an array of strings.
char*c[]={"cat","dog","mouse","fish"};
// ...some code here...
puts(c[i]);

you can reduce 2 bytes. However, this is slightly more tricker to get right. This usually only works when the length of the strings in the array only differ by 2 at most.
The '.' characters are padding that allows you to access each "substring" within the string using a multiple of a fixed offset.
char*c="cat\0..dog\0..mouse\0fish";
// ...some code here...
puts(c+6*i);

If the order of the strings do not matter, it is best to place the longest string at the end as, you may be able to save some bytes worth of padding.
char*c="cat\0.dog\0.fish\0mouse";
// ...some code here...
puts(c+5*i);

This is a useful trick that I have used to reduce quite a lot of bytes in the following answers.
`lol` is an ambigram, `dad` isn't
Can the chefs go?

Using a string instead of a list of ints also saves bytes for any number between 10 and 94 (printable ascii range is 32-126) because you can use just one character for those where otherwise you'd need 2 (i.e. 34 becomes B because it's the 34th printable ASCII character)

Omit Array Length
If you don't mind possible undefined behavior, define an array C[] (compiler assumes to have one element) and then rely upon the adjacent memory as usable space.
C[];main(){...}

Try it online!

Omit return
Surprised that only this answer provided a similar situation
Instead of return x; in the end, use g=x; where g is a global variable.
In other situations, it may be more shortened. Refer here for more about this.

https://codegolf.meta.stackexchange.com/a/24058/112488

the second link is seems to be broken

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/