I do this one of two ways.
Indent adjusted paste
First, if the code in the buffer is formatted, but at a different level of indentation, I use ]p instead of p, which pastes the code as is, but with the indentation shifted such that the first line pasted is the same depth as the line I'm on.
E.G. source copied to buffer
while (1) { dostuff(); }
E.G. result of pasting it with ]p
int myfunc() { int i = 5; /* Cursor on this line before paste */ while (1) { dostuff(); } }
vim puts the while at the same indentation level as int i. This is quick, but only works if the copied code is properly indented within itself.
Reformat after paste
The = operator in vim reformats the code based on the configured formatting rules. For short snippets of pasting, I'll go into visual mode with v, select the lines I just pasted and then press = to reformat them.
For larger pastes, I take advantage of the fact that the cursor goes to the first pasted line, and that vim says something like "84 more lines". I can then enter 84== to reflow those 84 lines (of course, substitute 84 with the number of lines you actually paste).
References
:help ]p for adjusted indent paste
:help = covers ={motion}, [count]== and {Visual}= for filtering through custom or builtin indent rules