text:
Scrolling Marquee
Following my entry to the Obfuscated Hello World I thought it might be fun to share the underlying code. But why just show the code, lets make it a golf too!
Challenge
Write a script that scrolls a string across the terminal, from right to left, settling on the left side.
Input
Takes a string as an argument.
Result
Prints the scrolling marquee to STDOUT. Max width of ~50 chars. Starts with 0 or 1 char showing. Some space between letters while scrolling. Stops when settled (having no extra space between word chars). Slow scroll, but not too slow (< 1s per iteration).
Example
Running script with arg 'Hello World'
                                                   H

later
                H    e    l    l    o         W    o

later
H    e    l    l    o          W    o    r    l    d

later
Hell    o         W    o    r    l    d

finally
Hello World

For a running example, try my code from the "Hello World" challenge. Eventually I will post mine. It currently is 202 chars in Perl. Now that there are some competitors, I have posted mine in the answers.
Winner
I don't want the restrictions to be absolute, that's why I left them a little vague. The shortest script which follows the spirit of my original will win.
Notes
This game assumes xterm environment. Should another environment prove useful, only similar environments will be compared and a separate winner may be declared for each.
Addendum (April 25, 2012)
To address some budding issues, I'm making a ruling. Your character count must include code needed to:

Flush STDOUT (Looking at you Ruby)
Implement sleep with time delay of <1s (Looking at you Perl)

This may be done as command line switches to an interpreter, but those characters count in the total (sans surrounding whitespace).

I'm a little concerned about terminal behaviors for this kind of thing...xterm, vt102, ...?

I'm assuming xterm, but I don't think it matters too much. Perhaps I don't understand your concern?

These tricks are usually produced by relying on the way various terminals handle some of the non-printing characters, and terminals differed in what they could do and what sequences produced the effects. For reproducibility it might be good to have a specified terminal environment.

It'll serve you right is someone posts a really short answer that depends on an obscure terminal that you don't have an emulator for, but OK.

ok I think I have it now. Thanks for the thoughts :-)

python 2 - 146 chars
edit: made it a function instead of input through stdin. first argument is the string, and the second argument is the length you want it to be. so invocation would be f('Hello World', 50). I also made it much smoother; when each character 'landed' there was an awkward pause
import os,time
def f(x,n):
 y=' '*n+'  '.join(x);z=0
 while y:w=y[0]==x[z];y=y[1+w:];z+=w;os.system('cls');print((x[:z]+y)[:n]);time.sleep(0.1)

old, 158 chars:
import os,time,sys
x=' '.join(sys.argv[1:])
y=' '*50+'  '.join(x)
z=0
while y:z+=y[0]==x[z];y=y[1:];os.system('cls');print((x[:z]+y)[:50]);time.sleep(0.1)

Using bash (at least in a recent installation of MacOSX and CentOS), the shell command used to clear the terminal screen should be 'clear' not 'cls'.

'cls' for windows, 'clear' for OSX/Linux builds, I guess

Advice how to start the program for those not dealing with python on a daily basis, would be helpful. Start python. paste code, call f("Hello World, 40) worked for me.

@user I um. I did put invocation up there?

Ruby, 93 91 89 chars
u="\1";s=u*50+[*$*[0].chars]*(u*3);$><<s.tr(u," ")[0,50]+" \r"while s.sub!u,""*sleep(0.1)

The text to be displayed must be given as command line argument, e.g.
ruby marquee.rb "Hello World"

for the example shown above. Unfortunately I cannot show the animation here, so you have to try out the code yourself.
Previous version:
s=" "*67+[*$*[0].chars]*"   ";(s.size*3/4).times{|j|s[j/3]='';$><<s[16,50]+" \r";sleep 0.1}

Impressive size. Its not very smooth though, is that me (I'm on a pretty low-power machine at the moment) or is that how the code works?

Figured it out, I had to set STDOUT.sync=true; so that it autoflushes. The Perl equiv is $|++. Thats an additional 17 chars, but still well below mine. Well I can't have Ruby beating Perl! Gonna hafta get working. Nice one.

If I call ruby1.8 "Hello World" I get, not exactly to my surprise, an error saying: ruby1.8: No such file or directory -- Hello World (LoadError)

@userunknown maybe you should put the path to the source file in there, too: ruby foo.rb args ;-)

@padde: Yes, I should. Unfortunately Howard edited his post without informing me about his change. Have a look at the history to understand my question.

@userunknown i understand, sorry for that.

@Howard +1, this is really nice. I tried really hard to shave off a char here and there but this is the best it gets.

@JoelBerger: It's very jumping for me too. Just 4 pictures, before the String reaches the final position, reproducible.

C, 94 83 80 173 chars
EDIT: Added lots of code, implements all the requested functionality now.
The constant 1e8 can be tweaked to control the speed. On my machine, it's quite fast as it is.
Some characters can surely be saved here. l can be static (saves initialization), c can become a pointer (replacing b+c).
char b[99],c=1;
main(a,t,w,i,l)char**t;{
    for(l=0;b[l++]=*t[1]++;b[l++]=32);
    for(w=80;i--||
        printf("\033[F\033[K%*.*s\n",w-=ll+6||
        b[++c]&&memmove(b+c-1,b+c,l););
}

Old version (80 chars), with partial functionality:
Saved a couple of chars by replacing char**t with int*t. Works fine in 32-bit (int**t would support 64-bit).
main(i,t,w)
    int*t;
{
    for(w=80;i--||printf("\033[F\033[K%*s\n",w,t[1],i=1e8)*--w;);
}

K&R C -- 431 416 characters
Respects the standard to a high degree. Uses ncurses so it should be largely terminal independent. There is a slight stuttering when the text hits the side due to some trickery played to preserve the intended whitespace in the string.
The string to use should be passed as the first argument on the command line (and should be escaped if it contains spaces, more so if it contains a ! as my test string (Hello, World!) did).
#include <ncurses.h>
#include <unistd.h>
#define T usleep(1e5),S(l)
#define U mvprintw(23,0,"%s",l),refresh()
char l[63],*p,*q,r;
S(char*s){r=0;if(*s==32)q=s++;else{for(;*s-32||*(s+1)-32;s++);
for(q=s;*s==32;s++);(s-q)&1?s--:usleep(1e5);}
for(r=0;*s;*q++=*s++){*s-32?r=1:0;}return r;}
main(int c,char**v){initscr();curs_set(0);for(c=0;c<62;l[c++]=32);
for(p=*++v;*p;){l[52]=*p++;U;T;U;T;U;T;}for(;T;U);getch();endwin();}

In a more readable and commented form:
#include <ncurses.h>
#include <unistd.h>

char l[63] /* take advantage of 0 initialization */,
  *p,*q, r;

/* Remove the first unwanted space. Unwanted means at the begining of
 * the line, all of even length blocks between non-spaces, and
 * all-bu-one of odd length blocks between non-spaces.
 *
 * Return true if the removed space occurs before a non-space character.
 */
S/*lide marquee*/(char*s){
  r=0; /* initialize the return value */
  if(*s==' '){
    q=s++;
  } else {
    /* Find the start of first block of contiguous spaces */
    for(;*s-' '||*(s+1)-' ';s++);
    for(q=s;*s==' ';s++); /* q holds the start, s finds it's end */
    /* if this block is even length remove all, if odd, all but one */
    if( (s-q)%2 )s--; else usleep(1e5);
  }
  /* copy from s to q all the way to the end */
  for(r=0;*s;*q++=*s++){
    if(*s-' ')r=1; /* note if we pass a non-space */
  }
  return r;
}

main(int c,char**v){
  initscr();curs_set(0); /* setup ncurses with invisible cursor */
  for(c=0;c<62;l[c++]=' '); /* initialize l */
  for(p=*++v;*p;){ /* load the message into the marque, skipping space */
    l[52]=*p++;
    mvprintw(23,0,"%s",l),
    refresh();
    usleep(1e5),
    S(l);
    usleep(1e5),
    S(l);
    usleep(1e5),
    S(l);
  }
  for(;usleep(1e5),S(l);mvprintw(23,0,"%s",l),refresh()); /* keeping sliding until we're done. */
  getch();
  endwin();
}

There's lots of potential for shortening, especially by replacing if with operators. For example - if((s-q)%2)s--;else usleep(1e5); -> s-q&1?s--:usleep(1e5); (or s-=s-q&1||usleep(1e5);)

@ugoren: Yup, and I had forgotten to replace the ' 's with numeric equivalents.

A few more tricks: Replace x==32 with x-32 (reverses meaning, so reverse if-else), or with x<33 (assuming 0..31 never used). Initialize with values you have (for(curs_set(c=0);...). *(s+1)->s[1]. Remove unneeded braces (replacing ; with , will help).

Perl 5.13.2, 96
$_=join$;x4,$;x46,split//,pop;print substr(s/$;/ /gr,0,50)." \r"while$|=s/$;//+select'','','',.1

Stealing a lot from @Kevin Reid's answer, especially the /r trick available in newer Perls.
Perl, 115
Like @Joel Berger's answer, this would become much shorter if I could use sleep 1 and be slow, or pass -MTime::HiRes=sleep on the command line to enable sleep.1.  Otherwise the only built-in way to get short sleeps is select'','','',.1 which is pretty long.
$|=@_=(($")x45,map{($")x4,$_}split//,pop);for(0..$#_){print@_," \r";splice@_,($_-=45)<0?0:$_/4,1;select'','','',.1}

Perl, 128
$_=$"x9 .pop;s/./    $&/g;$.=-46;$\=" \r";while($|=/./g){print substr($_,0,50);pos=++$.<0?0:$./4;s/\G.//;select'','','',.1}print

Perl, 133
$|=@_=split//,pop;for$i(reverse-$#_..50){for(@_){print$"x($j||$i),$_;($i+=$j=($i++>0)*4)>50&&last}print"    \r";$j=select'','','',.1}

yeah, I bit myself with my own rule on that one! I didn't realize that other langs would have a usleep built in. Oh well.

some suggestions, you can remove the space after each x and the block form of map will save a few.

bash 234
w=$1
p(){
i=$1
s=$2
p=$((50+s*3-i))
((p<s+1)) && p=$((s+1));
((p<50)) && echo -en "\e[20;"${p}H$3"  ";
}
clear
for i in {0..99}
do
for s in $(seq 0 ${#w})
do
p $i $s ${w:s:1}
done
sleep .1
echo -en "\e[20;1H  "
done
echo -en "\b\b$w\n"

Usage:
./marquee.sh "Hello, fine marquee world"

ungolfed:
#!/bin/bash
w=$1
p(){
    #si String index
    it=$1
    #it=iteration
    si=$2
    pos=$((50+(si*3)-it))
    ((pos<si+1 )) && pos=$((si+1));
    ((pos<50)) && echo -en "\e[20;"${pos}H$3"  ";
}
clear
for it in {0..99}
do
    for si in $(seq 0 ${#w})
    do
        p $it $si ${w:si:1}
    done
    sleep .1
    echo -en "\e[20;1H   "
done
echo -en "\e[22;1H"

It's not working on Ubuntu 20.04 bash version 5.0.17.

Yes, there where some \e missing, I don't know whether my error in transmition or maybe some database update in the last 9 years.

Awsome! It works.

JavaScript 180 218 chars
Production Version:
function f(){i--&&(i>50?h=h.substr(1):h=h.replace(" ",i==16?" ":""),document.body.innerHTML="
"+h.substr(0,50)+"
",setTimeout(f,99))}h=(new Array(50)).join(" ")+"HelloWorld".split("").join("   "),i=80,f()

Ungolfed Version:
h=new Array(50).join(" ")+("HelloWorld".split("").join("   "));
i=80;

function f(){
        if(i--){
            if(i>50){
                h=h.substr(1);
            }else{
                h=h.replace(" ",(i==16)?" ":"");
            }
            document.body.innerHTML="
"+h.substr(0,50)+"
";
            setTimeout(f,99);
        }
}
f();

Here is a jsFiddle Demo
Note: if you try to reproduce it, make sure the code is below the body

I can't tell from the demo, does it "stack up" on the left side, or simply make it to the left and then show the final string? Howard's definitely works if you are unsure.

@JoelBerger the hello world have 4 spaces between each letter, when the h is the first character, these spaces are removed. This demo is slower http://jsfiddle.net/fYvg7/1/

That's close, but you should remove each space individually.

@JoelBerger Fixed

Well I hate to be a nag, but one other problem: yours starts with all the letters showing rather than entering one-by-one on the right.

@JoelBerger No problem, I already had that, I think I remove it by mistake when shortening the code the last time, I will just make a rollback edit

Perl: 144 133
$|=@s=(($")x50,map{$_,($")x4}@i=split//,pop);{$n=0;$s[$n]ne$_?last:$n++for@i;splice@s,$n,1;print"\r",@s[0..50];sleep.1;$n!=@i&&redo}

In order to get the sleep of <1s though you need to run as:
perl -MTime::HiRes=sleep scriptname 'string to print'

Since I won't declare myself winner I won't argue myself over what counts there or not (but I really can't have Ruby win this ;-) )

4 more and it fits on a tweet :D

4 characters right here: s/' '/$"/g and s/shift/pop/

yeah, I had included those, along with removing the push statement. I just hadn't posted it yet.

Perl 5.13.2, 115 characters
$_=$"x9 .pop=~y/ /\0/r;s/./    $&/g;print(y/\0/ /r=~/(.{50})/,"\r"),select$.,$.,$.,.02while$|=s/ (\S)/$1 /g;print$/

Warning-clean.
Can be squeezed a bit by reducing the space between characters or the initial whitespace.
Requires Perl 5.13.2 or newer due to use of /r.
The substitution to NUL to preserve spaces is unambiguous since POSIX argv is not NUL-clean. However, the loop substitution will turn any other whitespace into nothing (eventually).

Credits:

$" as a source of " " taken from ephemient's answer, reduction by 1 character.

I love the r flag, best addition to the language since state

R, 319 characters
Following the philosophy of @Blazer example (d is the delay in sec):
f=function(x,n=50,d=0.2){
    s=strsplit(x,"")[[1]];i=1;l=length
    while (i<(n+l(s)-1)){
        if(i<=l(s))cat(rep(" ", n-i),s[1:i])
        else if((i<=n)&&(i>l(s)))cat(rep(" ", n-i),s[1:l(s)])
        else cat(paste(s[1:(i-n+1)],collapse=""),s[(i-n+2):l(s)])
        Sys.sleep(d);system("clear");i=i+1
    }
    cat(paste(s[1:l(s)],collapse=""))
}

Usage:
f("Hello World",n=20,d=0.2)

PowerShell, 135
Not very golfed and probably a horrible approach, but I'm sick and can't really think ...
for($x="`r"+' '*50;$y-ne$x){$y=$x
write-host($x=$x-replace' ([^ ])','$1 ')-n
if(!($t++%5)){$x=$x-replace'.$',"$args"[$i++]}sleep -m 99}

Q,145
Doesn't exactly meet the requirements because the final line removes all the spaces that were in the original input string.
{c:2_'((!)(#)a)_'a:((l:3*(#)x)#" "),\(1_(,/)b,'x,'b:" ");{(-1 x;);system"sleep ",($)y}'[-1_c,(l-1)$d(!:)[d]except\(&)(^)d:((!)(#)q)!q:last c;y];}

It takes two arguments, input string and scroll speed
q){c:2_'((!)(#)a)_'a:((l:3*(#)x)#" "),\(1_(,/)b,'x,'b:" ");{(-1 x;);system"sleep ",($)y}'[-1_c,(l-1)$d(!:)[d]except\(&)(^)d:((!)(#)q)!q:last c;y];}["hello";0.05]
             h
            h
           h
          h  e
         h  e
        h  e
       h  e  l
      h  e  l
     h  e  l
    h  e  l  l
   h  e  l  l
  h  e  l  l
 h  e  l  l  o
h  e  l  l  o
h e  l  l  o
he  l  l  o
he l  l  o
hel  l  o
hel l  o
hell  o
hell o
hello

unfortunately thats an important point. I know that the Perl scripts could get very small without it.

J (116)
s(echo@((50#LF)&,)@([[i.@]&2e7)@(50&{.)@;@:(([,~#&' '@])&.>))"1([-=&0@/:@\:@:~:&0)^:(i.>:+/k)k=.50,3#~<:#s=.>2{ARGV

Takes the input string on the command line, i.e. jconsole marquee.ijs 'Hello, world!'
If it doesn't need to clear the screen, i.e. output like this:
H  e  l  l  o
H e  l  l  o
He  l  l  o
He l  l  o
...

is allowed, it would be 12 characters shorter.
Explanation:

s.=>2{ARGV: get the string from the command line
k.=50,3#~<:#s: the starting amount of whitespace added before each character, 50 before the first one and 3 before all the others. (gives an array, '50 3 3 3...')
([-=&0@/:@\:@~:&0): given an array, decrements the first nonzero item in the array
^:(i.>:+/k): this function applied N times, where N is 0 upto the sum of the amount of added whitespace. (gives a matrix: 50 3 3 3; 49 3 3 3; 48 3 3 3; ... 0 0 0 1; 0 0 0 0).
"1: run following function on each row of the matrix
;@:(([,~#&' '@])@.>): add the given amount of spaces before each character in the string
(50&{.): take the first 50 characters of the string
([[i.@]&2e7): a function that generates the list from 0 to 2*10^7, and then throws it away. This takes about a third of a second on my machine, this causes the delay.
((50#LF)&,): add 50 newlines before the string, to clear the screen
echo: output the string
s (...): give the string as the left argument to the function

APL (70)
{⎕SM∘←1,⍨1,⍨,/D{⍺,⍨⍵⍴⍕⍬}¨P←⍵-{⍵×~×⍺}\×⍵⊣⎕DL÷8⋄0∨.≠P:∇P}1↓⎕SD,1↓3⍴⍨⍴D←⍞

Takes input from the keyboard, the output is in the ⎕SM window (which would be the terminal if you had a text-based APL I guess). The window size is detected automatically, if you really want it to be 50 change the 1↓⎕SD to 50.
Explanation:

1↓⎕SD,1↓3⍴⍨⍴D←⍞: read the string and store in D. Generate a vector describing how much whitespace to add before each character, which is the screen width before the first character (1↓⎕SD), and 3 before the others (1↓3⍴⍨⍴D).
⎕DL÷8: wait 1/8th of a second
P←⍵-{⍵×~×⍺}\×⍵: in the vector in the right argument, subtract 1 from the leftmost nonzero item, and store the new vector in P.
,/D{⍺,⍨⍵⍴⍕⍬}¨P: for each character in D, prefix the amount of whitespace given in P.
⎕SM∘←1,⍨1,⍨: display on the screen, in the leftmost column of the top row
0∨.≠P:∇P: if there is a nonzero element in P, repeat with P.

05AB1E, 42 bytes
ð¶:S3úJ46ú[D50£¶ð:D?IQ#ðõ.;“…¢('\r')“.eт.W

Try it online (without the sleep). NOTE: I don't have 05AB1E installed locally, so I'm not 100% sure if the \r trick works (in theory it should work, however). In TIO the \r are interpret as newlines instead. Also, the TIO uses the legacy version, because .e is disabled in the new TIO version (program is the same in both the legacy and new version of 05AB1E, though).
Explanation:
ð¶:            # Replace all spaces in the (implicit) input-string with newlines
   S           # Split the string to a list of characters
    3ú         # Pad each character with 3 leading spaces
      J        # Join the characters together again
       46ú     # And pad the entire string with an additional 46 leading spaces
[              # Now start an infinite loop:
 D             #  Duplicate the string
  50£          #  And leave only the first 50 characters of this copy as substring
     ¶ð:       #  Replace the newlines back to spaces
        D?     #  Duplicate the string, and print it without trailing newline
 IQ            #  If the current string is equal to the input:
   #           #   Stop the infinite loop
 ðõ.;          #  Replace the first space with an empty string to remove it
 “…¢('\r')“    #  Push dictionary string "print('\r')"
           .e  #  Evaluate it as Python code
 т.W           #  Sleep for 100 ms

See this 05AB1E tip of mine (section How to use the dictionary?) to understand why “…¢('\r')“ is "print('\r')".

Python, 139 bytes
import os;P='\n'
def f(x,w):
 v=k=P*w+P.join(x);o=str.replace
 while v!=x:os.system('sleep 1;clear');k=o(k,P,'',1);v=o(k,P,' ');print v[:w]

Has to call f('Hello World', 50) to start.

PowerShell, 129 bytes
for($x=' '*52+(($args|% t*y)-join' '*4);$x-match'  '){write-host "`r$(-join($x=$x-replace'(?<!  .*)  ')[0..50])  "-n
sleep -m 99}

Try it online!
This script does not remove spaces from the arguments in contrast to Joey's script.
TIO does not display the output correctly. With Powershell console, you get the scrolling marqueeline.


text:
Tips for golfing in <all languages>
The aim of this post is to gather all the golfing tips that can be easily applied to <all languages> rather than a specific one.
Only post answers that its logic can be applied to the majority of the languages

Please, one tip per answer

"Majority" by what metric?

@leftaroundabout by the metric of the same word

The problem is that many languages are (often short-lived) experimental ones with very untypical paradigms, for which typical programming expressions don't make any sense at all. So "majority of all languages" it virtually impossible to fulfill. You should restrict it in some way, e.g. to "majority of languages regularly used on codegolf.SE". At the moment, the answers look quite a lot like "the majority of remotely C-derived languages", but those, albeit the vast majority of all written code is written in them, are not the majority of languages.

leftroundabout, I guess we all know what they roughly mean. This is about mostly language-independent optimizations, i.e those not only useful in Brainfuck but maybe Python, C, Java and Fortran at once. General ideas that you can apply in many languages that work similarly. I don't think there is a need to be that precise and specific in [tag:tips] and a CW question. This is about helping others to golf, not about pissing them off.

Hopefully nobody creates a language called <all languages>...

Voting to close because most of the tips in this question will just be duplicated on the more dedicated tips page of any language they apply to.

Many answers here are very far from applying to a majority of languages.

Merge Loops
You can usually merge two consequent loops, or two nested loops, into one.
Before:
for (i=0; i<a; i++) foo();
for (i=0; i<b; i++) bar();

After:
for (i=0; i<a+b; i++) i<a?foo():bar();

ugoren the loops are still not the same. @Gaffi is right.

@kaoD, in both cases foo is called a times, bar is called b times. This is because in "after", the loop runs a+b times, the first a call foo, the next ones call bar.

I'm looking at this again (much, much later), and I don't understand my own question now. I maybe didn't understand the ternary operation before? The way I see it now, it makes sense.

Woops, I read that very late in the night. You're right!

Very similar: for(y=0;y<Y;++y)for(x=0;x<X;++x) can often become for(i=0;i<X*Y;++i) with x replaced by i%X and y replaced by i/X.

@Lynn See this Python tip for more info: http://codegolf.stackexchange.com/a/41217/34718

Just to mention the obvious:
Question your choice of algorithm and try something entirely new.
When golfing (especially harder problems that result in longer programs) all too often you might stick to the path you first chosen without trying other fundamental options. Of course, you may micro-golf one or a few lines at a time or a part of the overall idea, but often not try a totally different solution.
This was especially noticeable in Hitting 495 (Kaprekar) where deviating from the actual algorithm and looking for patterns you can apply to get to the same result was shorter in many languages (just not J).
The downside is that you possibly solve the same thing half a dozen times. But it works in really all languages except HQ9+ (where finding another way to output Hello World would be slightly futile).

+1 In addition to being good for golfing, this is good exercise for any programmer in many real-world situations!

Use Test-Driven Development
If the code must handle various inputs, then write comprehensive tests and make it easy to run them all very quickly.  This allows you to try risky transforms one baby step at a time.  Golfing then becomes like refactoring with perverse intent.

I use a spinoff of this method. Since the problems themselves are usually rather simple, I write a program that does the job. Usually this is "readably golfed", so that it's succinct, but newlines etc. are there. I copy this file to a new location and golf it, checking every now and then that the programs return same values for some chosen inputs. If I ever make a mistake leaving me with a broken program, no memory of what I changed and no understanding of my golfed piece, I have something of a "specification" saved as a reference source.

I love this method, which is one reason that I tend to include comprehensive test suites for all problems I write.

@RubberDuck The Do not repeat yourself principle is often strictly followed.

Try to reduce logical statements
For example, if A and B are booleans and your language treats booleans like numbers to some extent, A and (not B) and A>B are equivalent. For example in Python
if A and not B:
    foo()

is the same as:
if A>B:
    foo()

I'd never have thought of that.

B>A or foo() would be an even shorter way to express this, take advantage of lazy evaluation of boolean expressions to ensure it only calculates things when it needs to.

@scragar: Correct, but this is not the point of this tip. (It is a valuable independent tip though.)

@scragar, B>A or foo would evaluate foo if B==A which is not what we want. (Right?)

Also, if you have long imbricated conditions (say with 5/6 parameters), you can use a Truth table and a Karnaugh map to find the shortest boolean expression for it

Technically they are not equivalent, if A is false then B will not be evaluated in the first version.

@JayXon: Hence “if A and B are booleans”. If A and B are expressions, numbers, etc., you have to be more careful.

@Wrzlprmft I interpreted that as anything that evaluates to a boolean, like (1>0) or all([]) because in codegolf you want to inline as much as possible, so having a boolean variable is less common than expressions.

B>A and foo() would evaluate foo if and only if B>A.

Write an explanation of your code
Writing an explanation forces you to thoroughly look at each part of your code again and to make your thoughts and choices in writing a certain passage explicit. In doing so, you might find that different approaches are possible which may save some bytes, or that you subconsciously made assumptions which don't necessarily hold.
This tip is similar to Question your choice of algorithm and try something entirely new; however, I have found that the step of actually writing down how each part is supposed to work is sometimes crucial for becoming aware of alternatives.
As a bonus, answers including an explanation are more interesting for other users and are hence more likely to be upvoted.

+1 See also, README Driven Development.

Initialize variables using values you already have.
Instead of x=1, try to look for something that already equals 1.
For example, a function's return value: printf("..");x=0; -> x=!printf("..");.
It's easiest with 0, because you can always negate, or when all you need is the right truth value (and don't care if it's 1 or 19).

in C you can use argc from main as 1. see: http://codegolf.stackexchange.com/questions/1034/reinvent-the-for-loop/5642#5642

@std''OrgnlDave, True, but this question is about things common to all languages.

Use unary ~ for x+1 and x-1
This trick applies to languages that have a unary bitwise negation operator ~ and a unary regular negation operator -.
If your program, by chance, contains the expression -x-1, you can replace it with ~x to save bytes. This doesn't occur all too often, but watch what happens if we negate (-) both expressions: x+1 equals -~x! Similarly, x-1 equals ~-x. (Think of which way the tilde points: right is +, left is -.)
This is useful, because in all languages I can think of that have these operators, they have higher precedence than most operators. This allows you to save on parentheses. Watch how we save four bytes here:
(x+1)*(y-1)     ==>    -~x*~-y

Squeeze whitespace
Know the rules for whitespace in your language. Some punctuation marks, or other characters, might not need any surrounding whitespace. Consider this Bourne shell function:
f () { echo a; echo b; }

In Bourne shell, (); are metacharacters, and do not need surrounding whitespace. However, {} are words and need whitespace unless they are next to metacharacters. We can golf away 4 spaces next to ();, but must keep the space between { and echo.
f(){ echo a;echo b;}

In Common Lisp and PicoLisp, () are metacharacters. Consider this code to find the average of two numbers:
(/ (+ a b) 2)

We can golf away 2 spaces.
(/(+ a b)2)

Some languages have strange and subtle rules for whitespace. Consider this Ruby program, which prints the sum and product of a line of integers.
#!ruby -an
i=$F.map &:to_i
puts"#{i.reduce &:+} #{i.reduce &:*}"

Each & needs a space before itself. In Ruby, i=$F.map &:to_i means i=$F.map(&:to_i) where & passes a block parameter. But, i=$F.map&:to_i means i=$F.map.&(:to_i) where & is a binary operator.
This weirdness happens in languages, like Perl or Ruby, that use ambiguous punctuation. If in doubt, use a REPL or write short programs to test the whitespace rules.

Why does there need to be a space between "{" and "echo", but not between ";" and "echo"?

I used the terms from the manual for OpenBSD sh(1), which says that "{" is a reserved word and ";" is a meta-character. Because of this, "{echo" is one word but ";echo" is two words. Other manuals might explain this differently. Also, the Z shell zsh has different rules.

assign functions new names if used multiple times
x = SomeLongFunctionName
x(somedata)
x(somemoredata)
etc

Only if we use enough calls to x.

Single Letter Variable Names
You have 52 of them; use them all! Don't be afraid to try different approaches and compare lengths. Know the language and the specific shortcuts/library functions available.

26 for non-case-sensitive languages. :-)

Often $ and _ can be used as identifiers.

@Gaffi: And more than enough for languages which allow Unicode identifiers, unless the task limits you to ASCII or counts bytes rather than characters.

If you're counting bytes instead of unicode then using extended ascii might be a way to squeeze another ~120 identifiers if you need them(not that for a golf script you should need more than 26 anyway)

not even considering that you can use the same name on different scopes, or reuse a variable you don't need anymore

@ is a valid variable name in T-SQL, use it instead of @a.

54 (plus in some languages ones with diacritics) in JS.

Use the conditional operator.
A conditional operator
bool ? condition_true : condition_false

is more beneficial, character wise, than an IF statement.
if(a>b){r=a;}else{r=b;}

can be written as
r=a>b?a:b;

Languages that don't have a ternary can use a&&b||c instead. Slightly longer, but still shorter than an if.

Then again, some can't use either option (VBA comes to mind), but both are still good suggestions. :-)

Gaffi: VBA has Iff, although it's a function, so subject to evaluation of all arguments.

Using ternary in if statements can also be very helpful if(a ? b : c)

@MichaelKohl note that a&&b||c can return c when a is true iff b is false, a little edge case, but we shouldn't forget that ^^

@MichaelKohl Katenkyo's comment (what they meant, with more detail): Worth noting that, if a == 1 && b == 0, then both b and c will be evaluated. Here is the expression, with parens: ((a) && (b)) || (c). a&&b's result will be 0 in this case, so c will be evaluated, because the || gate will check for the second operand if the first one is 0.

Read the question carefully
Code golfing is as much about understanding the question (what is asked and what is not asked, even though it would be implied in any other setting) as producing code that (may) only satisfy what is asked.
Any input other than what is explicitly asked for need not be handled. If there are some test cases and no generic requirement, your code may only work in those cases. Etc.
e.g. if the question says "print the prime numbers from 1 to 100 inclusive", the largest prime printed will be 97 and you can change your loop end condition from 100 to 97 and save 1 byte. The question does not say you need to test 98, 99, 100 for primality, so don't do that.
e.g. 2. if the question says "print these numbers" then it does not say your answer must calculate the numbers. It might be shorter to store the expected output and decode and print it, than to write a calculator for it, e.g. storing 97 98 99 100 as a string of ASCII characters 'abcd'.

I think a better headline here would be "Don't handle non-required edge cases". The phrase "Try to find loopholes" brings to mind ways to avoid doing what is specified through some artful reinterpretation of the rules, whereas what you are offering is merely the good advice not to over-implement your solution.

Yes, but an artful reinterpretation of the rules is part of code golfing as well! (0 char solutions, etc.)

That would/should be a different answer, though. There's a fundamental difference between, for example, implementing a solution that only works for ints because OP didn't require float support, and an answer that prints the text "any prime greater than 100" because "you didn't say it had to be an actual prime number".

I think some OPs include a "Test cases subject to change; your code must still work after the change" notice, and really change them if they see just one answer hard-coding the testcases.

use - instead of !=
for numeric comparisons:
If a equals b, a-b results in 0, which is falsy. Anything else than 0 is truthy; so
if used in a boolean context, a-b <=> a!=b
If you use it with if/else or with the ternary operator, this can also save you one byte for equality:
a==b?c:d <=> a-b?d:c

Double check your character count
Sounds like a no-brainer, but by being careful you might be able to "save" a few characters by not actually doing anything!
If you're using Windows, you may be inputting \r\n instead of just \r or \n when you hit Return - adding an extra byte per line! Turn control characters just to double check you're not doing this.
In Notepad++ you can convert all \r\n line endings to just \r by going to Edit > EOL Conversion > UNIX/OSX Format.
Also make sure you don't include any trailing whitespace in your character count! The line feed on the bottom line in your code is also inconsequential, so that won't need to be counted either.

I don't think I've ever seen a case where this has actually counted...

I've just had this problem myself (hence why I'm adding it).

Use > and < instead of >= and <=
When checking against hard-coded integer values, use > and < instead of >= and <= where possible. For example, using
if(x>24&&x<51)

Is 2 bytes shorter than using
if(x>=25&&x<=50)

Related: If you are sure an outcome can't be negative, you could use <1 instead of ==0 as zero-check (or >0 instead of !=0 for the mirrored check).

Shouldn't you add a note about x being an integer?

Use bitwise operations for checking numbers between 0 and any 2n-1
Might be a bit of an edge case, but it could come in handy sometimes. It relies on the fact that all numbers to which m=2n-1 applies have the rightmost n bits set to 1.
So, 710 == 000001112, 1510 == 000011112, 3110 == 000111112 and so on.
The trick is x&~m. This will return true whenever x is not between 0 and m (inclusive), and false otherwise. It saves 6 bytes from the next shortest equivalent expression: x>=0&&x<=m, but obviously only works when m satisfies 2n-1.

Greater/Less than to save a digit:
//use:
if(n>9){A}else{B}
//instead of:
if(n<10){B}else{A}

Just remember to swap the code from if to the else and they will do exactly the same thing (or switch the sides of the inequality)!
Note: this can be applied with any power of 10 and their negatives: ...-100, -10, 10, 100...
(source link)

I'm not sure I understand the point of this. What does this reduce from?

@Gaffi you save one character and they do exactly the same

vs. what alternative? Sorry, not trying to be obstinate, I just don't get it. (newb, here, apparently...)

@Gaffi the second line is shorter than the first one (count them if you don't believe me)

Ah, I see. Works on any integer transition from 9 to 10, 99 to 100, etc. Sorry that took me so long! (I say integer only, because I can see an issue with n = 9.5...)

Also in some languages(if supported) if your numbers are large/small enough the scientific notation may actually save you some chars instead: if(n>99999) vs if(n<1e5)

@scragar That would produce a float instead of an int .

Only works if n is an int.

Understand what other people did
In addition to being fun, if you examine other people's code, you can sometimes discover a good algorithm that you didn't think about, or a trick (sometimes an obvious one) that you overlook.
Sometimes there is an existing answer that you can translate to another language, and benefit from the other language's goodies.

Reuse function parameters instead of new variables

Well for example, in C, your main function is always passed the number of arguments supplied to the program (which is 1 - the program name - by 'default') so with main(i){... you now have a variable with the value of 1 without having to do any assignments. 2 chars saved there..

I think it's quite specific to the C. Script languages don't need declarations, and in most compiled languages defining a variable isn't longer than defining a parameter.

in java when needing a array inside a function which has same type as one parameter you can save off a few bytes by putting that parameter as last and make it a vararg parameter; (used that to shave off some bytes on a function to find longest word in a sentence)

Avoid premature loop breaks
If running through a loop to check for 1 or more instances of a boolean check, it might make for a more efficient program to exit the loop on the first true value. However, removing the break and looping through all iterations allows for shorter code.
int main() {
bool m = false;
int n = 1000;
for (int i = 0; i < n; i++) {
if (i >= 100) {
m = true;
break; // remove this line
}
}
return 0;
}

You can also simplify the if statement away in these cases: m|=i>=100. (And you can also simplify the i>=100 to i>99 in this case but that's not very relevant here)

know your operator precedence
Whenever You combine several expressions, check the operator precedence table for your language to see if you can reorder stuff to save parentheses.
Examples:

In all languages that I know, bitwise operators have a higher precedence than boolean operators:
(a&b)&&c needs no parentheses: a&b&&c just as (a*b)+c does not.
a+(b<<c) can be rewritten as a+b*2**c.
That doesn´t save anything for this example, but it will if c is a small integer literal (<14).
Bitwise operations have a lower precedence than most arithmetic operations, so if your language implicitly casts boolean to int, you can save a byte on a<b&&c<d with a<b&c<d (unless you need the short circuit evaluation)

Use unary ~ for a-b-1 and a+b+1
In addition to @Lynn's suggestions regarding x+1 → -~x; and x-1 → ~-x, you can also golf a-b-1 and a+b+1.
a-b-1    // 5 bytes
a+~b     // 4 bytes

a+b+1    // 5 bytes
a-~b     // 4 bytes

It might look like a tip you won't use all that often, kinda like using ~x instead of -x-1 doesn't happen often, but I've used it enough times to see it as a useful tip here. Especially with array-indexing you might use these above in some cases.

Split strings for long arrays
Most languages have a way to split a string into an array of strings around a token of some kind. This will inevitably be shorter than an array literal once the length reaches a language-dependent threshold, because the extra overhead per string will be one copy of a one-char token rather than (at least) two string delimiters.
E.g. in GolfScript
["Foo""Bar""Baz""Quux"]  # 23 chars

becomes
"Foo
Bar
Baz
Quux"n/  # 20 chars

For some languages, the threshold is as low as one string. E.g. in Java,
new String[]{"Foo"}  // 19 chars

becomes
"Foo".split("~")  // 16 chars

The notable exception is Ruby, which provides an array-of-strings literal which automatically splits on spaces at the cost of two bytes: %w{Foo Bar Baz Quux}.

Perl provides something similar: qw(Foo Bar Baz Quux) becomes a list of strings.

@BenGoldberg: Although for Perl, you often want to avoid even qw, using barewords that aren't existing functions as strings, or using glob operations, either of which saves even the qw, e.g. (Foo,Bar,Baz,Quux) or <Foo Bar Baz Quux>

Shorter for-loops
If you have X statements {inside} your for-loop, you can move X-1 statements (inside) the for-loop after the second semicolon for(blah;blah;HERE) to save 3 bytes. (separate the statements by using a comma ,)
Instead of
for(int i=0;i<9;){s+=s.length();println(i++);}

you can move one of the statements into the for-loop's ( braces) while leaving the other out
for(int i=0;i<9;println(i++))s+=s.length();

and save 3 bytes (saved 1 more byte thanks to @ETHProductions)

Put simply,
instead of
for(blah;blah;){blah 1;blah 2;...;blah X}

move the statements around so you end up with this
for(blah;blah;blah 2,...,blah X)blah 1;

and save 3 bytes

And if the for is the final statement, the ; becomes optional

O(n^2) is your friend
You spend your time looking to get rid of O(n^2) algorithms and bring runtime and memory use down; golf turns that around - spend freely of CPU and Memory to bring code size down. Use nested loops, calculate 10x too much data instead of a complex exit condition, call sort() every loop iteration instead of storing the result.
Some questions have a runtime limit to push you to write a more efficient answer, even then knowing how fast your language and code runs can give you room to take liberties and still stay within it.

Rely on the compiler to provide the required performance.
Be sure to know which optimisations are guaranteed by the compiler and at which optimisation levels, and use them liberally. And even if performance isn't a concern requirement, you can still test with optimisations on, and then only discount one character because your code is still technically valid without the compiler flag.
Consider the following Haskell function to compute 2^n (ignoring the fact that Haskell already has a built-in exponentiation operator or three) (23 characters):
p 0=1;p x=p(x-1)+p(x-1)

The problem is - it's horrendously slow, it runs in exponential time. This might make your code untestable or to fail any performance constraints given by the question. You might be tempted to use a temporary variable or an immediately invoked function literal to avoid repeated function calls (25 characters):
p 0=1;p x=(\y->y+y)$p$x-1

But the compiler can already do that for you, you just need set -O as a compiler flag! Instead of spending few extra characters per site to eliminate common subexpressions manually, just tell the compiler to do basic optimisations for you.

Shouldn't the first example just be p(x-1)*2?

Maybe somewhat obvious but...
Make use of operator return values
Keep in mind that the assignment operator returns a value!
For example, if you want to add y to x and then check if x is greater than something, you can do
if(25<x+=y)

instead of
x+=y;if(x>25)

Or maybe you want to find the length of a string after trimming it:
strlen(s=trim(s))

Rather than
s=trim(s);strlen(s)

In which language can you do assignment inside a call? or is that a keyword arg?

I think assignments are expressions (with the assigned variable's new value as their expression value) in at least C, C++, C#, and Java. a = (b=c)+1; sets b to c, and then sets a to b+1.

@Lynn Try a=1+b=c. And you can add PHP and JavaScript to your list.

Ruby does this the best. It gives the = operator a higher precedence on the left than the right, so 1+x=2 is valid and evaluates to 3

@Cyoce afaik it´s that way in all languages where an assignment is an expression.

Most of these tips are pretty obvious but still helpful :-)

Compress or/and streaks
Simple trick I've come up with when trying to squeeze a long streak of conditions chained by ands (or ors, in this case just substitute 'all' with 'any').
Eg:
if a>0 and a<10 and a+b==4 and a+3<1:

Becomes
if all([a>0,a<10,a+b==4,a+3<1]):

That's a cool one, I'll have to try it!

Which languages have an all(array-of-Booleans) built-in?

Ruby has it. [a>0,a<10,a+b==4,a+3<1].all?

Although if this were Python you'd be using something like if 10>a>0 and a+b==4>1>a+3:

@PeterTaylor Haskell has too

@Sp3000 actually, if 10>a>0>a+2 and a+b==4: because a+3<1 is a+2<0. which on second thought, isn't possible, so if 0:. XP

In K, "all" is &/ (AND reduce) and "any" is |/ (OR reduce). Most APL derivatives have an equivalent juxtaposition.

JavaScript (ES6) lets you do [someArray].every(_=>_) for and and [someArray].some(_=>_) for or. Of course, if you use this more than once, you should alias i=_=>_

Python also has all().

@mbomb007: It does, but the folks mentioning what you'd do in Python were pointing out that the example golfs better using chained conditionals.

Utilize language version / compiler / environment quirks / new features
This is especially useful for polyglots, but can be applied to other challenges. Sometimes, a compiler bug can golf off a byte, a implementation bug can allow you to save a few chars, or a really bleeding-edge feature can improve your score.

Use truth tables
An example condition can be (((A AND B) OR (A OR B)) AND C) OR (A OR C) with A, B and C being boolean variables. But it's so long! Is there any way to shorten it, and prove it acts the same after shortening? Well, truth tables to the rescue!

A
B
C
D=A AND B
E=A OR B
F=D OR E
G=F AND C
H=A OR C
I=G OR H

0
0
0
0
0
0
0
0
0

0
0
1
0
0
0
0
1
1

0
1
0
0
1
1
0
0
0

0
1
1
0
1
1
1
1
1

1
0
0
0
1
1
0
1
1

1
0
1
0
1
1
1
1
1

1
1
0
1
1
1
0
1
1

1
1
1
1
1
1
1
1
1

The truth table above represents the possible values and outcomes of the example condition we specified earlier. D, E, F, G and H are variables which make our life a lot easier. You can see what they're assigned to at the top row of the table. The final variable, I, is the outcome of the condition. So, now that we have the outcomes handy, we can simplify the table to just the base variables and the final outcome:

A
B
C
I

0
0
0
0

0
0
1
1

0
1
0
0

0
1
1
1

1
0
0
1

1
0
1
1

1
1
0
1

1
1
1
1

We can now relatively easily see that the condition above really reduces to just A OR C.

One can also try and ask WolframAlpha.

@JonathanFrech But how are you going to prove it then? ;)

Outsource the proof and trust.

@JonathanFrech Sorry, but you must be able to prove your answers by yourself, and Wolfram|Alpha doesn't have a proof, so I'm afraid it isn't going to help you much. :)

Using a K-map would be more systematic and guarantees an optimal solution.

Know the difference between "program" and "function" in your language
Many questions on codegolf.SE ask you to "write a program or function"; this gives you some freedom to play to the strengths of your language and runtime based on how it handles command line parameters, how much boilerplate it needs for defining functions and their parameters, for defining full programs, for reading user input in a running program.
e.g. for a question asking you to write a program or function which takes a number as input, multiplies it by 10 and prints the result:
in Python it might go this way:
print(10*int(input()))    # full program
lambda x:print(10*x)      # function

in APL, the other way:
⎕←10×⎕      # full program
{⎕←10×⍵}    # function

In languages with a lot of code to get a whole program to run such as Java, a function could be much shorter. In more dynamic scripting languages such as Perl with many command line options to change how the code acts, a full program with a command line switch could be the shortest. Taking input from an implicit $args might be shorter than input(), or defining a function with a parameter might be shorter than System.Console.ReadLine();

Use bitwise operators in your if statements
In an if statement, you can (usually) use the bitwise operator "and" (usually & , if it is present) rather than && or and and save 1-2 bytes. Sames goes with other keywords (not is the same as a bitwise ! or ~ in many languages (saves 2 bytes), or is bitwise | in many languages (saves 1 byte), etc.).

Optimize Imports
Use glob imports over specific symbols, especially if you need multiple symbols from the path.
In rust:
use library::some_function; //bad: 25 bytes
use library::*; //good: 13 bytes

Renaming long symbol names may also be able to save you bytes if you use the symbol multiple times.
In rust:
//bad: 100 bytes
use library::*;
fn main(){
    some_very_long_function_name();
    some_very_long_function_name();
}
//good: 76 bytes
use library::some_very_long_function_name as f;
fn main(){
    f();
    f();
}

If you only use a symbol once, using its fully qualified pathname will save bytes.
In rust:
//bad: 48 bytes
use library::*;
fn main(){
    some_function()
}
//good: 41 bytes
fn main(){
    library::some_function()
}

Which techniques to use varies widely based on the language, what symbols you use, and how you use them. If your use case is complicated trying multiple styles will help you find the shortest. Also, make sure you know your language- they all have their own quirks. For example, Java supports glob imports and fully qualified paths but not symbol renaming.

Combine multiple/nested if checks using And/Or when possible.
i.e.:
if (a && (b || c)) {

}

instead of:
if (a) {
    if (b) {
        //Do Stuff
    } elseif (c) {
        //Do same stuff
    }
}

Also, use bitty conditionals (&, `|) to remove more characters.

Although using bitwise & instead of && removes 1 character in some cases it messes up the operator precedence and you will have to put parentheses to make it work.Use it wisely.

eval() is perfectly safe
In more dynamic languages it can help to make a string of code and then eval() it (or the equivalent in your language), as a way to repeat chunks of code by inserting the code into the right places as a string replace without the overhead of defining and calling functions, or to loop N times without loop boilerplate.
e.g. in Python to print "hello" five times:
for i in range(5):print("hello")

exec('print("hello");'*5)

e.g. in PowerShell calling [math]::Truncate() three times becomes slightly shorter as a function, and slightly shorter again doing a string replace on code and then evaluating it:
$a=[math]::Truncate($a/$b);$b=[math]::Truncate($c/$a);$c=[math]::Truncate($d/$e)

function T($a,$b){[math]::Truncate($a/$b)};$a=T $a $b;$b=T $c $a;$c=T $d $e

'$a=T($a/$b);$b=T($c/$a);$c=T($d/$e)'|% r*ce T [math]::Truncate|iex

Don't be afraid to put non-printables in your code.
Sometimes, instead of using escapes like \0, \x1f, \033, \n, or \u0003, you can just put the codepoint in the string verbatim. You may need to input code points manually using keyboard shortcuts, a hex editor, or a good old printf "\x1f" >> file
Note that you cannot copy and paste null bytes on Windows.
Since Stack Exchange doesn't play well with non-printables (and they are difficult to read), I like to represent them by <kbd> tags: (make sure to use language-all and escape < and > in the code block)
<!-- language-all: lang-c -->
<pre><code>char str[]="abc<kbd>00</kbd>def";</code></pre>

char str[]="abc00def";
This is very useful for making lookup tables in languages where strings can be indexed like arrays for their codepoint, such as C, C++, asm, C#, and Python (with b''), since the non-printables consist of the first 32 bytes.
int l[]={2,9,31,7};l[x]; // 23 bytes
"02091f07"[x]; // 10 bytes

This also can apply to invalid UTF-8 sequences, but that is very fragile in practice and far less useful.

Find better ways to initialise your variables
Some other answers came close to mentioning this already, but in many (strictly typed?) languages, it's shorter to initialise x as empty string like:
x:=""

or x as empty rune (char) like:
x:=''

than
var x string

and
var x rune

Using preexisting values is obviously preferred, but not so easy.

Use LF instead of CRLF
If you use CRLF line endings, each newline will count as two characters. Changing this to LF will save one character per newline in your code.

This works even for some unexpected languages. QBasic's editor uses CRLF, unsurprisingly for a language that was distributed with DOS. But if you create a file with LF line endings in a different editor, QBasic will run it just fine.

duplicate-ish

Don't declare variables in for-loops
If for-loops have one statement inside of them, you can move the iterating variable's initialisation with the other variables that you already have declared.
int a=1;for(int i=1;i<n;)a*=++i;  // 32 bytes
int a=1,i=1;for(;i<n;)a*=++i;     // 29 bytes

Also, if you have multiple un-nested for-loops, it would be better if you reuse the same variable. This sort of ties in with this answer.
int a=1;for(int i=1;i<n;)a*=++i;for(int j=2;j<n;)a-=j++; // 56 bytes
int a=1,i=1;for(;i<n;)a*=++i;for(i=2;i<n;)a-=i++;        // 49 bytes

(I know you can do a=i=1, but that is not the point)

Now if you don't have any statement before the for-loop (and you only have 1 for-loop), it would be best to initialise the variable inside the for-loop
for(int i=0;i<99;)i*=2;       // 23 bytes
int i=0;for(;i<99;)i*=2;      // 24 bytes

for some language you can just for(int a=1,i=1;i<n;)a*=++i;for(i=2;i<n;)a-=i++; and using a and i outside is fine

Using float -> integer conversion automatic truncates for flooring (positive values) in most languages that don't strongly enforce types:
f.floor     # Ruby
f.to_i      # -1 byte
int $f      # Perl
0|$f        # -2 bytes
parseInt(f) # Javascript (Never use Math.floor)
0|f

This will truncate downwards (for positive values), and to get the ceil instead, it can be achieved with the same trick by reflecting the value across 0 (not true in all languages / implementations, not always shorter):
(i/5.0).ceil # Ruby
-(i/-5)
0-i/-5       # for integers of i, provided by ShadowRanger

For the languages with true floor (as opposed to truncating) division (e.g. Python, Ruby), you can shave an extra character off -(i/-5) by subtracting from 0 instead of using parentheses to apply proper precedence, e.g. using 0-i/-5.

@ShadowRanger Thanks! I added it to the answer. That's a new thing I've learned, wow!

Abs
Instead of
i<Math.abs(n)

,writing
i<n|i<-n

is shorter in some languages
EDIT:
i*i<n*n

is usually shorter suggested by ceilingcat

Use magic numbers / magic strings
Code golfers tend to forget using magic numbers while they're golfing, so I'm putting some ways to make magic numbers here.

The easiest way a magic number can be used is if the list or string you need to encode is one of two values (and then you can use bit-shifts and logical and to access the bitwise values stored in the magic number).

e.g. this answer is a pretty good usage of this type of magic numbers.

You can also construct magic numbers/strings via brute force or a similar method.

E.g. this answer

plenty of larger powers (^) where an alternative representation is a lot cleaner :
   2 ^         10 ->  4^5
   2 ^         16 ->  4^8 (also 2^2^2^2)

   2 ^         12 ->  8^4
   2 ^         15 ->  8^5

   2 ^         24 ->  8^8
   2 ^         32 -> 16^8
   2 ^         48 ->  8^16
   2 ^         64 -> 16^16

   2 ^        256 -> 2^4^4 (also (4^8)^16, or 16^64)
   2 ^       1024 -> 2^4^5

   2 ^        128 -> 4^8^2 (also 16^32)
   2 ^       4096 -> 2^8^4
   2 ^       8192 -> 4^8^4

   2 ^         48 -> 8^4^2
   2 ^      65536 -> 2^4^8 (also 2^2^2^2^2)

   2 ^        512 -> 4^4^4
   2 ^     131072 -> 4^4^8

 even ridiculously large powers such as

   2 ^   16777216 -> 2^8^8
   2 ^   33554432 -> 4^8^8

   2 ^     524288 -> 4^4^9
   2 ^  268435456 -> 4^8^9

   2 ^ 1073741822 -> 2^(8^10-2) # very close to exponent
                                # upper limit of GMP

Overloading for function
I find useful for golfing to use as C++ templates and give to the sys the chance of create function for the type (it would reduce the code written by one human).
Too if there are + function that use + or - the same algorithm, write all in one function only, that depends from one parameter for say what result one want. In this way recently condense 3 function in one with near 50% written code less; reference palpn() function in codegolf.stackexchange.com/a/148745/58988 .

Can you give example of your recent answer?

@user202729 The function palpn() in https://codegolf.stackexchange.com/a/148745/58988 it would reassume 3 function "find next palindrome", "find previous palindrome" "say if arg it is palindrome"

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:
Constant output program
I was wondering how one might go and produce a program that takes input from some kind of random source and uses it to produce constant output. An obvious way is, for example, to take an integer x and output x/x for 1, but that isn't too clever, is it? Therefore, the task is to write a program that outputs the same thing, no matter which input is given to it.
Specifications

The program may assume that the input is either a number or a one line string (that is, valid characters are [a-z][A-z][0-9] and spaces). If you adopt one of those restrictions, specify which in your answer.
The program must use the entered input in some way. To put it more formally, the contents of the variable that takes the input must be used afterwards in some calculation that affects the final variable to be printed.

The winner will be the most upvoted solution.

x/x for 1 doesn't work with 0/0

The challenge is contradictory, if you say it has to affect the final variable to be printed, and meanwhile it has not. There is no way to get around that: If the input is the output, there is no influence.

After reading a comement to another post, I get another impression of the task: Fox input 7, output might be 7, and for input 8, output has to be 8 too, then? I thought in the beginning that we have to output the input.

+1, because when I first read the question I wanted to -1 and flag, but then I read the answers it provoked.

Python
This question is boring.  I'd rather sleep.
from time import sleep
sleep(input())

Input a number.

So the output is... consistently... nothing?

@GigaWatt: yes indeed!  My guiding principal here was: ask a stupid question, get a stupid answer.  Honestly, I thought the question would be closed before I got any upvotes.

GolfScript
~{.3*){.2%}{2/}until.@=!}do

This program will take a positive integer as input, and will output 1 unless the input is a counterexample to the Collatz conjecture.  While the Collatz conjecture remains an open problem, it is known that there are no counterexamples below 5 × 260.

Shouldn't it not halt for counterexamples. So really, it will always output 1.

Perl
<>/0

produces for any input string:
Illegal division by zero at test5.pl line 1, <> line 1.

it's not code golf

Ruby
def a(x)
  4
end

I somehow felt this was related:

Python
n=input()
p=37
print (n**p-n)%p

Takes an integer input, and always outputs 0.  Uses Fermat's little theorem, which states that n^p == n mod p.

J
=

Usage:
   =10
1

Always outputs 1.
Or how about an unhappy smiley verb:
{:0[

Usage:
   {:0[ 147
0

Always ouputs 0.

That's not what = does. You're thinking of =~. Practically (but not semantically) they're the same thing when your input is one integer.

@Eelvex Yes, I was thinking of =~. I've removed the incorrect bit from my answer.

C
This program reads an integer from stdin and then prints that integer, right?
main() {
    int i;
    printf("%d\n", scanf("%d", &i));
}

Well, no. It just prints 1.
The input must be an integer though (otherwise it may output 0 or -1), which proves that the program "uses" the input.

um... isn't it UB to point to the argument space? For one, it's not possible with regcall.

Maybe. Then why would you use regcall?

Ok, on a (slighly) more serious note, I just used the argument because I'm lazy. Its use is besides the point really. I'll change it if it makes you happy.

Javascript
var input = ~~prompt("Input an integer!");
if(Math.abs(input)<=Math.pow(2,31))
  console.log("It's too small! (not bigger than 2^31 = "+Math.pow(2,31)+")");
else console.log("It's quite big!");

Though JS can represent any integer between ±9,007,199,254,740,992, it will always print

It's too small! (not bigger than 2^31 = 2147483648)

because bitwise operation is performed in range of 32bit.

Ruby:
p !gets

Always outputs false. gets takes user input, ! negates that and since strings are truthy, the result will be false.

What about empty strings?

@Timtech p !"" #=> false.

Hmm, wasn't aware of that.

What else did you expect? Everything in Ruby that's not false or nil is truthy, the empty string's no exception.

Python 2
x=input()
print x^x

Only accepts integers. always outputs 0 by xoring itself

APL
⍴⍣≡

⍴ is the shape function, ⍴⍣≡ is the fixpoint of the shape function.
All APL values have a shape. Say, a 4x6x8 array has shape 4 6 8; a scalar (like 3) has shape ⍬ (no dimensions). Therefore, ⍴ always returns a one-dimensional list. This means that applying the output of ⍴ to ⍴ will always get you a one-dimensional list with one number in it. That means that applying ⍴ again will always get you a one-dimensional list with the number 1 in it.
Therefore, ⍴ converges to 1; therefore ⍴⍣≡ will give 1 for all possible inputs.

Golfscript
.=

Accepts any input and always prints 1.

It doesn't really use the input though.

@MrZander: Well, the criteria for what counts as using the input or not are quite vague. I'd say that if dividing by itself is OK, comparing to itself should also be fine.

Python
def f(x):
    return 0*x

f(1e+300/1e-300) returns nan.

You just blew my mind.

Thinking about it though, I guess that's ok: "valid characters are [a-z][A-z][0-9] and spaces", apparently floating point is out. So +1 for a simplistic yet working solution!

JavaScript
var input = prompt("Input something!");

console.log(new Number(input) === 1);

Will always return false, even with the input 1

Golfscript (4 chars)
~1\?

Accepts an integer. Outputs 1.

Perl
$a=<>+1;for(1..length$a){$a=length$a}print$a

This program does use the input number, and it always prints 1.

Python
This one works for numbers only.
I can't prove that it works for all numbers (can anyone?), but it prints "False" for all cases I've tested.
EDIT: Fixed a bug in the last line.
p=lambda x:x>1 and (i*i>x for i in xrange(2,x+1) if x%i==0 or i*i>x).next()
q=lambda x:(i<x for i in xrange(2,x+1) if p(i) and p(x-i) or i==x).next()
x = input()
print x%2==0 and x>2 and not q(x)

Explanation (for those who think my Python code is unclear):
p(x) tells you if x is a prime.
q(x) looks for two primes, whose some is x.
The program prints True if the number is even, greater than 2 and not the sum of 2 primes.
Please tell me if you find such a number.

We probably won't find such a number: http://en.wikipedia.org/wiki/Goldbach's_conjecture

I was about to say 4, but then I thought, 2 is prime :)

Python
print float("inf")*sum(map(ord,raw_input()))

Always returns 'infinity'.

Q
Returns 1. Where no parameters are declared, Q implicitly uses x,y& z where appropriate. I think this satisfies the second condition...
{1}

Python
print input()*0

C
Produces 1 (prints and returns) for every input. (Input being the number of command line args)
j;main(c){j=0;while(c){j+=c%2;c/=2;}return j^1?main(j):printf("%d",j);}

This program does the same #error 1 but cannot properly speaking be said to take input (unless you count the rest of the program after as input).

Python
print eval('42#'+raw_input())

Accepts any input

PostScript
This function takes one argument of any type, actively discards, and will always output , unless you didn't supply it with enough arguments (which I am going to define as being undefined behavior for this function), depending on the value of the argument. Here is its implementation:
/f {pop} def

This function will always take one more argument than is currently on the stack, so it will always output a stackunderflow error, depending on the input.
/f {clear pop} def

And here is a third, even more useful function, which I will define as having undefined behavior, depending on the number, types, and values of the arguments.  Here is its implementation:

Common Lisp
(unless (read))

Always returns nil (unless you crash it with stupid input)

Brainf**k
Since the question is self-contradictory it's hard to give a serious answer, so here it is:
,[[->+<],]>[<->+<+>--<+>][->+>+[-]>+>+<<<<][->-<]+>[<->[-]]>[->--<----]+>[[---<->+<+>-]<->]>>[+>-<--]+>[[-]<->]<<[->-<-->+++>>>>>+<<<->+<<<+++++[>>++++++<<]]+>[<+>-]++>+<-<->>>>+<<<<->+<+>->>>[<]>[>]<[<[->-<]+>[<->[-]]<]+[>+>+>+>+<<---<<[-]]>>++<<[>>+[+<<<-]>>-<[<]+<<[<<->+]]>[->>+<<]>>[->+<]>[>+++++++++++<-]>[->+>+>+<<<]>[.>]

Accepts any string or number as input, always outputs "!!!". Have fun figuring out what it does.

Clojure
(and(read-line)0)

Crudely equivalent to the prior common lisp submission, except that it makes no attempt to ensure that the line "read" is valid in any way shape or form. Compiled or interpreted, this program will read a single line and exit 0 in all cases.

Game Maker Language
if argument0 return argument0/argument0 else return argument0

It can be any script, just call script(argument) - it returns true if the number is not 0, else it returns false
If this was code golf, it would be if argument0 a=1 return a which is 25 characters when compiled with the option "Treat all uninitialized variables as value 0".

I forgot to add, the input must be a number.

C++
Accepts any input.  Prints ASCII equivalent of each character entered:
#include <iostream>
#include <string>
using namespace std;

int main() {
  string s;
  cout << "Enter a string: ";
  cin >> s;

  cout << "ASCII characters of input:\n";

  for (int i = 0; i < s.size(); i++)
    cout << s[i] << ": " << int(s[i]) << endl;

  return 0;
}

Befunge
&@

always returns nothing.

And a less pointless version:
&>:v
 -
 ^1_.@

Always returns 0

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


text:
Anti-aliasing ASCII art
Background
ASCII art is the practice of creating images by using ASCII text to form shapes.
Aliasing is the effect created by the large "pixels" of ASCII art, which are the size of characters. The image becomes blocky and hard to see. Anti-aliasing removes this effect by creating a gradient and by softening the hard edges of the ASCII art.
The Challenge
Your challenge is to write the shortest program possible that will take a piece of ASCII art and will output a version that has been anti-aliased.
What sort of anti-aliasing?
All of the ASCII art will consist of two types of symbols: Spaces and non-whitespace. For each non-whitespace character, your program must determine whether it is in a position where it need to be anti-aliased. If it is, then you need to replace it with the correct character. If it isn't, then the character stays the same.
How do you know if a character needs to be anti-aliased? The answer depends on the characters that are immediately above, below, left, and right of the character (not the diagonals). Here is a chart of when anti-aliasing is required, where ? and x can stand for any non-whitespace character.
 x? ->  d?
 ?      ?

?x  -> ?b
 ?      ?

 ?      ?
?x  -> ?F

 ?      ?
 x? ->  Y?

 x  ->  ;   Note: This character has been changed from _ to ;
 ?      ?

 ?      ?
 x  ->  V

?x  -> ?>

 x? ->  <?

 x  ->  @

Input (and example pre-anti-aliasing ASCII art)
First, there will be two lines of input (to STDIN), a number H followed by a number W. There will then be H lines of exactly W characters each (excluding the newline). These following lines will be the ASCII art that needs to be anti-aliased. Here is an example input (not beautiful, but a test):
7
9
  888888
 888888
999 98  7
 666666
  666666
   6666
    6

Output (and example anti-aliased art)
Your program should output to STDOUT the ASCII art (of the same dimensions), which has been anti-aliased. Here is the output for the above input. Notice how the the border characters are treated as bordering whitespace.
  d8888>
 d8888F
<99 98  @
 Y6666b
  Y6666>
   Y66F
    V

This might not look that good (due to the space between lines in the code block), it looks better with larger ASCII art, and the quality depends on the exact font used.
Another Example
Input
12
18
   xx  xxx  xxx
  xxxx  xxx  xxx
 xxxxxx  xxx  xxx
xxx  xxx  xxx  xxx
xxxx xxx  xxx  xxx
 xxxxxx  xxx  xxx
  xxxx  xxx  xxx
x  xx  xxx  xxx  x
xx    xxx  xxx  xx
xxx  xxx  xxx  xxx
xxxx  xxx  xxx  xx
xxxxx  xxx  xxx  x

Output
   db  <xb  <xb
  dxxb  Yxb  Yxb
 dxxxxb  Yxb  Yxb
dxx  xxb  xxb  xxb
Yxxb xxF  xxF  xxF
 YxxxxF  dxF  dxF
  YxxF  dxF  dxF
;  YF  dxF  dxF  ;
xb    dxF  dxF  dx
xxb  <xF  <xF  <xx
xxxb  Yxb  Yxb  Yx
Yxxx>  Yx>  Yx>  V

Rules, Restrictions, and Notes
Your program should be written in printable ASCII characters only, so that we can make art out of the programs. Other than that, the standard code-golf rules apply.

Since there are no answers yet, I have changed one character in the anti-aliasing chart. _ has become ; because it works better.

This might be my favorite code golf question of all time.  Working on like 4 different awesome solutions.

Although I am confused. You say diagonals don't count, but your diagrams all show question marks filling out the diagonals. From what I see in the examples, it may be safe to only look to the sides, but I get confused? Do diagonals ever matter?

No, the diagonals never matter. It will probably be more clear if I removed the diagonals from the chart.

I think there might be a typo in your example; I believe the right-hand column should have Ys on the inside edge. Enjoyed coming up with the answer to this one though, good question :D

Sorry. I'll fix that.

Ruby, 180 168 characters
gets
w=1+gets.to_i
f=*(readlines*"").chars
f.zip(f[1..-1]+s=[" "],s+f,s*w+f,f[w..-1]+s*w){|a,*b|$><<"@;V#{a}>bF#{a}<dY#{a*5}"[a>" "?(b.map{|y|y>" "?1:0}*"").to_i(2):3]}

Another Ruby implementation which takes a zip approach. You can see the second example running online.
Edit: Using readlines saves 12 characters.

Ruby 275 265 263 261 258 254 244 243 214 212 207
H=0...gets.to_i
W=0...gets.to_i
G=readlines
z=->x,y{(H===y&&W===x&&' '!=G[y][x])?1:0}
H.map{|j|W.map{|i|l=G[j][i]
G[j][i]="@V;#{l}>Fb#{l}<Yd#{l*5}"[z[i+1,j]*8+z[i-1,j]*4+z[i,j+1]*2+z[i,j-1]]if' '!=l}}
puts G

Sample 1: http://ideone.com/PfNMA
Sample 2: http://ideone.com/sWijD

Parenthesis around the range definition are not necessary. 2) 0..h-1 can be written as 0...h. 3) G=[];h.times{G<<gets} can be written as G=readlines, similarly as in your C# code. 4) After step 3. variable h becomes useless, h and w's values are used only once, so h=gets.to_i;w=gets.to_i;H=(0..h-1);W=(0..w-1) can be written as H=0...gets.to_i;W=0...gets.to_i. 5) In this case and can be written as &&, which not needs the spaces around. 6) You have an extra ; and you counted the newline at the end of file, which are not necessary. This mean 214 chars: http://ideone.com/CiW0l

Wow, thanks! I knew there were improvements to be made, but never thought there were that many. I had tried H=0..gets.to_i when I wrote the code, but it didn't seem to work (obviously it must've been for other reasons).

Still two points where you can reduce by at least 7 chars: 1) You can use map instead of each 2) z=->... instead of def z...end.

@Howard Thanks, I've applied the map instead of each change. For the lambda syntax, however, I think that would require the usages of z to be of the form z.call(args) instead of z(args), thus adding a bit to the character count. Please let me know if I'm missing something.

@Howard Nevermind, I just found out what I was missing. I'll update to use the lambda [] usage.

Python, 259 chars
H=input()
W=input()+1
I=' '.join(raw_input()for i in' '*H)
for i in range(H):print''.join(map(lambda(s,a,b,c,d):(s*5+'dY<'+s+'bF>'+s+';V@'+' '*16)[16*(s==' ')+8*(a==' ')+4*(b==' ')+2*(c==' ')+(d==' ')],zip(I,I[1:]+' ',' '+I,I[W:]+' '*W,' '*W+I))[i*W:i*W+W-1])

The program reads the input into a single string I (with spaces separating the lines), zips up a list of 5-tuples containing the character and its four surrounding characters, then looks up the result character using string indexing.

Javascript, 410 characters:
function(t){m={"10110":"b","11100":"d","01101":"Y","00111":"F","10100":";","00101":"V","00110":">","01100":"<","00100":"@"},d="join",l="length",t=t.split('\n').splice(2),t=t.map(function(x)x.split('')),f=function(i,j)t[i]?(t[i][j]||' ')==' '?0:1:0;for(o=t[l];o--;){for(p=t[o][l];p--;){y=[f(o+1,p),f(o,p+1),f(o,p),f(o,p-1),f(o-1,p)],t[o][p]=m[y[d]('')]||t[o][p]}}t=t.map(function(x)x[d](''))[d]('\n');return t;}

ungolfed:
function(t){
    m={
        "10110":"b",
        "11100":"d",
        "01101":"Y",
        "00111":"F",
        "10100":";",
        "00101":"V",
        "00110":">",
        "01100":"<",
        "00100":"@"
    },
    d="join",
    l="length",
    t=t.split('\n').splice(2),
    t=t.map(function(x) x.split('')),
    f=function(i,j) t[i]?(t[i][j]||' ')==' '?0:1:0;

    for(o=t[l];o--;){
        for(p=t[o][l];p--;){
            y=[f(o+1,p),f(o,p+1),f(o,p),f(o,p-1),f(o-1,p)],

            t[o][p]=m[y[d]('')]||t[o][p]
        }
    }
    t=t.map(function(x)x[d](''))[d]('\n');
    return t;
}

Original, 440 characters:
function (t){m={"10110":"b","11100":"d","01101":"Y","00111":"F","10100":";","00101":"V","00110":">","01100":"<","00100":"@"},s="split",d="join",l="length",t=t[s]('\n').splice(2),t=t.map(function(x) x[s]('')),f=function(i,j)i<0||i>=t[l]?0:(j<0||j>=t[i][l]?0:t[i][j]==' '?0:1);for(o=t[l];o--;){for(p=t[o][l];p--;){y=[f(o+1,p),f(o,p+1),f(o,p),f(o,p-1),f(o-1,p)],h=m[y[d]('')];if(h){t[o][p]=h}}}t=t.map(function(x) x[d](''))[d]('\n');return t;}

N.B. I've assumed that the first two input lines are actually irrelevant and the size of the following lines are a correct. I'm also reckoning I might be able to chop a few more chars off this when I get a chance!

Replace the declaration of m to m={22:"b",28:"d",13:"Y",7:"F",20:";",5:"V",6:">",12:"<",4:"@"} then convert m's subscript with parseInt(): m[parseInt(y[d](''),2)]. This reduces the size to 373 characters.

PHP - 359 330 282 268 257 characters
<?php
$i=fgets(STDIN)+0;$w=fgets(STDIN)+1;$s='';$m='@<;d>0b0VY00F000';
for(;$i--;)$s.=fgets(STDIN);
for(;++$i<strlen($s);){
$b=trim($s[$i])?0:15;
foreach(array($i+1,$i+$w,$i-1,$i-$w)as$k=>$x)
$b|=pow(2,$k)*(isset($s[$x])&&trim($s[$x]));
echo $m[$b]?$m[$b]:$s[$i];}

@PhiNotPi It wasn't working because my locally saved test files had windows-style EOL \r\n. I updated my code to work with unix style EOL \n.

Ok, it seems to be working now.

Python, 246 241
H=input();W=1+input()
S=' '
o=W*S
F=o+'\n'.join((raw_input()+o)[:W-1]for k in range(H))+o
print ''.join((16*x+'@;<d>b'+2*x+'V'+x+'Y'+x+'F'+3*x)[
16*(x>S)|8*(a>S)|4*(l>S)|2*(r>S)|(b>S)]for
x,a,l,r,b in zip(F[W:-W],F,F[W-1:],F[W+1:],F[2*W:]))

WC and test on sample 2, diffed with the output of the Ruby solution at the top:
t:~$ wc trans.py && python trans.py < lala2 > o && diff -q o ruby_out2_sample
  2 11 241 trans.py
t:~$

C# 591 563
string A(string t){var s=new StringReader(t);var h=int.Parse(s.ReadLine());var w=int.Parse(s.ReadLine());var lines=s.ReadToEnd().Split(new[]{"\r\n"},StringSplitOptions.None).Select(x=>x.ToCharArray()).ToArray();for(var i=0;i<h;i++)for(var j=0;j<w;j++){var c=lines[i][j];if(c==' ')continue;var n=(i>0?(lines[i-1][j]!=' '?1:0):0)+(i<h-1?(lines[i+1][j]!=' '?2:0):0)+(j>0?(lines[i][j-1]!=' '?4:0):0)+(j<w-1?(lines[i][j+1]!=' '?8:0):0);lines[i][j]=new[]{'@','V',';',c,'>','F','b',c,'<','Y','d',c,c,c,c,c}[n];}return string.Join("\r\n",lines.Select(l=>new string(l)));}


text:
Play Connect 4!
Write a program to play the game of Connect 4.  You are given the state of the board as input and you must decide which column to place your piece in to either get 4 in a row (horizontally, vertically, or diagonally) or block your opponent from doing the same.
The board is a 6x7 array, where each cell may be empty (' '), contain your piece ('X') or your opponent's piece ('O').  An example board:
O
XX    X
XOX  OO
XOO OXO
OXXOXXO
XOXOXOX

You would want to play in column 3 (columns are 0-6, numbered from the left) for the diagonal win.  So you output:
3

Your code must output a column number, and it must satisfy the following criteria:

You cannot play in a column that already has 6 pieces in it.
If there is at least one winning move, you must play one of them.
If you can prevent your opponent from winning on his next move, you must do so.

Note that optimal play is not necessary, only that you take an immediate win or prevent your opponent's immediate win.  If your opponent has more than one way to win, you need not block any of them.
You are given the board on standard input and must print a column number in which you want to play on standard output.  The board is guaranteed to be well-formed (no holes, at least one possible move) and to not already have a win for either player.
Shortest code wins.
Example 1
      X
      O
      X
      O
 OOO  X
 XXX  O

You must play either column 0 or 4 for the win.
Example 2
      X
X     X
O     O
XOX  XO
XXO XOX
XXO XXO

You must play column 3 to block your opponent's immediate win.
Example 3
X
XO
OX    O
XO   XX
XXO OOO
OOO XXO

You cannot win or stop your opponent from winning, so you may play any column 1-6 (0 is full).
Example 4
X
O
X
OOO
XOX
OXOX

You cannot play in column 3, as it lets your opponent win immediately.  You may play in columns 1-2 or 4-6.

C, 234 286 256 chars
Fixed to correctly solve the problem, by checking for opponent winning moves following every move attempted.
This code is very sensitive to the input file format - each line must conatain 7 chars + newline.
The board is treated as an 8x8 matrix, rather than 7x6. The 8th column contains the newlines, and the 2 extra rows contain zeros, so they don't interfere with the solution. They actually help - When moving right from the rightmost column, you hit to newline column, which serves as a boundary check.
w checks one position for an opportunity to win or block. q should be the cell to check around. It uses reursion to loop through 4 directions (starts with 9,8,7, then several times 1).
C checks for a sequence of identical characters starting at q in direction d, both back and forth. It returns the sum of both sequences (not counting the starting position), so if it returns 3, there's a row of 4.
char B[99],q;
C(i,d){
    return B[d*i+++q]-B[q]?d>0?C(1,-d):0:1+C(i,d);
}
w(x){
    return x&&C(1,x>6?x:1)>2|w(x-1);
}
t(l,c,r,v){
    for(;c--;)B[q=c]&32&B[c+8]-32?r=w(9,B[c]=l)?v=c:v||r*t(79,l,0,1)?r:c,B[c]=32:0;
    return r;
}
main(){
    putchar(48+t(88,16+read(0,B+16,48),0,0)%8);
}

Python 2.x - 594 591 576 557 523 459 458 433 bytes
This is the best I've achieved so far. I guess it's hard to beat C. Awesome challenge, I have to say.
r=range
f=[]
exec'f+=list(raw_input());'*6
def n(p):
 o,b,a,k=[],1,'O',lambda q:any([o[i:i+4]==list(q)*4for o in(f[x-x%7:],f[x%7::7])for i in r(3)]+[all(q==f[7*(y+u*i)+z+i]for i in r(4))for u,z,v,c in((1,0,3,4),(-1,3,6,3))for y in r(z,v)for z in r(c)])
 for x in r(42):
    if x>34<a>f[x]or x<35and f[x+7]>'0'>f[x]:f[x]=p;z=k(p)*b;o=z*[x]+o+[x]*(a==p or n(a)[1]);b-=z;f[x]=' '
 return o[0]%7,b
a,b,c,d=n('X')+n('O')
print(a,(c,a)[d])[b]

The  if-line (line 7) has indentation of one tab. SE doesn't like tabs.

I spend way too much time refining these. Also, the 458 byte version didn't work correctly for example #4. Take 25 bytes away and it does. Magic.