Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position asterisk near to variable name when declaring pointers in C in vscode auto formatting?

Currently if I write int * ptr; then auto-formatting would convert it to int* ptr; which I don't want. After googling a bit, I found here the fix for that. I have to use PointerAlignment: PAS_Middle. But I don't know where to add that.

In vscode settings, I tried to add it in C_Cpp: Clang_format_fallback_style and C_Cpp: Clang_format_style. Neither didn't work. There was no save/apply button in settings, so I hope it would automatically update settings as soon as change it. But nonetheless, whenever I format my C code using Shift+Alt+F, it puts asterisk near to the type!

like image 915
Sourav Kannantha B Avatar asked Dec 04 '25 06:12

Sourav Kannantha B


2 Answers

I solved it in this way: Tools > Options > Text Editor > C/C++ > Code Style > Formatting > Spacing. At the end of the list from the right window there is a "Pointer/reference alignment" section, select there the option you like.

Ok. I found why it was not working. Because, below it C_Cpp: Formatting was set to vcFormat and not clangFormat. But changing it to clangFormat didn't seem to work. Instead it would refuse to format at all!!

Then I had to search below the setting related to this. I found Pointer Reference Alignment. But sadly, instead of setting it to center, I had to set it to ignore since center would convert int *const ptr; to int * const ptr;

EDIT: Thanks to @Shawn in comments for pointing me towards .clang-format file. I was able to use clangFormat now in vscode. But it was inconsistent across different files in different folders of a same project! I don't know if it's fault of clang-format or vscode. For now, I'm falling back to using vcFormat.

like image 27
Sourav Kannantha B Avatar answered Dec 07 '25 03:12

Sourav Kannantha B