If you don't mind that the behavior will only be almost, but not quite the way you described it, there is a built-in way to do this. This is an automatic printing feature that can be activated using the Cc Ca key combination or on this .emacs line:
(c-toggle-auto-newline 1)
The difference is that it will do reformatting right after entering the opening bracket {. When you finally enter the closing piece, it will also retreat correctly.
You also need to set the correct CC mode style. The cc-mode style seems to define things the way you described it. You can activate it using the Cc . key combination Cc . and then select cc-mode or the .emacs line
(c-set-style "cc-mode")
The c-mode functions are automatically loaded and therefore usually will not be available when loading the .emacs file. So you have to wrap them in a hook for c-mode, like this
(add-hook 'c-mode-hook (lambda () (c-toggle-auto-newline 1) (c-set-style "cc-mode")))
Rรถrd source share