Don't indent Xcode-style commented-out code - xcode

Is there currently a way (other than explicitly suppressing formatting for a code segment) to get clang-format to not indent Xcode-style commented out code? That's // at the beginning of the line:
int f()
{
// return 1;
return 2;
}
Xcode does this comment-out style on Cmd+/.
clang-format, when run, indents the comment:
int f()
{
// return 1;
return 2;
}
which Xcode still successfully uncomments-out using the same shortcut, but resulting in inconsistent indentation:
int f()
{
return 1;
return 2;
}
I tried (ab)using CommentPragmas for this purpose, unsuccessfully. I thought maybe I'm doing the spaces in the regex wrong, but even with CommentPragmas: '^aaaa':
int f()
{
//aaaareturn 1;
return 2;
}
gets indented to
int f()
{
//aaaareturn 1;
return 2;
}
So either I'm still doing something wrong, or CommentPragmas will still indent comments, even if not otherwise re-flowing them.

Related

scanf,fgets, fgetc get skipped inside loop

Im trying to make a recursive menu.
This program will later work with a tree(hojanodo), thats why I keep track of the root.
Problem: For some reason the fgets/fgetc is being skipped inside the recursivity on the second run, why does this happen?
I want the user to input either 1,2 or 3.(int)
What would be the fix for this? and is this the best way to implement a menu?
Here's what I have right now:(It compiles and runs so you can test it out but doesn't really work like I would like to..)
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
char ch;
int i;
struct node *left;
struct node *right;
}hojaNodo;
int handle_menu(int eventHandler, hojaNodo **root);
int opcion_menu();
char get_symbol();
int get_userMenuInput();
int intro();
int main(){
hojaNodo *treeRoot = NULL;
intro();
// system("clear");
handle_menu(opcion_menu(), &treeRoot);
return 0;
}
int opcion_menu(){
int userOption;
printf("1.Agrega un Simbolo.\n");
printf("2.Listar Codigo\n");
printf("3.Exit");
userOption = get_userMenuInput();
printf("User: %d",userOption);
if(userOption < 4 && userOption > 0){
return userOption;
}
else
return -1;
}//eof opcion_menu
int handle_menu(int userOption,hojaNodo **root){
hojaNodo *tempRoot = NULL;
tempRoot = *root;
int valor;
char simbol;
switch(userOption){
case 1:
simbol = get_symbol();
printf("Simbol: %c", simbol);
break;
case 2:
printf("List Nodes\n");
break;
case 3:
printf("Exit");
userOption = -1;
// destroy_tree(root);
break;
default:
printf("userOption Error, Bye!");
break;
}//eof switch
if(userOption != -1)
handle_menu(opcion_menu(),&tempRoot);
// return userOption;
return -1;
}//eof menu()
char get_symbol(){
/*char userKey[3]
fgets(userKey,len,stdin);*/
char simbolo;
printf("Give me a symbol.");
simbolo = fgetc(stdin);
return simbolo;
}
int get_userMenuInput(){
char userKey[3];
int userOption;
size_t len;
len = sizeof(userKey);
fgets(userKey,len,stdin);
userOption = atoi(userKey);
//printf("User Option: %d\n", userOption);
return userOption;
}
Well apart from all the comments related to recursion and other changes suggested, please check this out. fgets() function needs flushing the input stream. It can be done using fflush() or fgetc().
A simple solution would be:
In function:
int opcion_menu(){
...
fgets(userKey,2,stdin);
fgetc(stdin); // Add this statement
Also in function:
int handle_menu(int userOption,hojaNodo **root)
case 1:
printf("Give me a choice : ");
fgets(userKey,2,stdin);
fgetc(stdin); // add this statement
fgets reads in at most one less than size characters from stream and stores them into the buffer pointed to by string. This will lead the newline character still available in Input Stream which need to be flushed. If this newline character is not read from Input stream, than this would become the input for next fgets function and ultimately it will skip the fgets(since it has already got its input a newline character)
fgetc(stdin) will flush out these extra newline character.
I don't know if this might help anyone.
In my case, I had to 'free' the buffer from the char with this function:
void clean(){
char cTemp;
while((cTemp = getchar()) != '\n')
;
}
Im not really sure why this works but it does(if anyone does, please add it to my answer).
I call it right before I call get_userOption();

How to record the running information of functions in your program?

I recently attended a coding interview and I was asked a question which I didn't know the answer to. After searching the answer on the internet for a few day, I come here call for help.
The question is described as followed: You should propose a approach to record the running information of function in your program, for example, the times of a function called, and so on.
By the way, you are not allowed to modify these functions. Maybe you want to define a global variant in these function to record the running function, but that is not allowed.
Ok! That's all about the question I met in a coding interview.
This is the best I could come up with using C++ macros. I don't know whether it conforms to the requirements.
A very basic version just recording the count. The macro replaces all existing calls to the function with the contents of the macro, which records the stats and calls the function. Can easily be extended to record more details. Assumes there's only one function with that name or you want one count for all of them. Requires a macro for each function.
// here's our function
void func()
{ /* some stuff */ }
// this was added
int funcCount = 0;
#define func(...) do { funcCount++; func(__VA_ARGS__); } while(0)
int main()
{
// call the function
func();
// print stats
cout << funcCount << endl;
return 0;
}
Prints 1.
A more generic version. Requires changes to how the function is called.
// here are our functions
void someFunc()
{ /* some stuff */ }
void someOtherFunc()
{ /* some stuff */ }
// this was added
map<string, int> funcCounts;
#define call(func, ...) do { funcCounts[ #func ]++; func(##__VA_ARGS__); } while(0)
int main()
{
// call the functions
// needed to change these from 'someFunc();' format
call(someFunc);
call(someOtherFunc);
call(someFunc);
// print stats
for (map<string, int>::iterator i = funcCounts.begin(); i != funcCounts.end(); i++)
cout << i->first << " - " << i->second << endl;
return 0;
}
Prints:
someFunc - 2
someOtherFunc - 1

XTend For-Loop Support and Adding Range Support

I can't seem to find a great way to express the following in Xtend without resorting to a while loop:
for(int i = 0; i < 3; i++){
println("row ");
}
println("your boat");
So, I guess my question has two parts:
Is there a better way to do the above? I didn't see anything promising in their documenation
A large portion of the features the language has are just Xtend library extensions (and they're great!). Is there range() functionality à la Python that I don't know about?
I ended up rolling my own and got something like the following:
class LanguageUtil {
def static Iterable<Integer> range(int stop) {
range(0, stop)
}
def static Iterable<Integer> range(int start, int stop) {
new RangeIterable(start, stop, 1)
}
def static Iterable<Integer> range(int start, int stop, int step) {
new RangeIterable(start, stop, step)
}
}
// implements Iterator and Iterable which is bad form.
class RangeIterable implements Iterator<Integer>, Iterable<Integer> {
val int start
val int stop
val int step
var int current
new(int start, int stop, int step) {
this.start = start;
this.stop = stop;
this.step = step
this.current = start
}
override hasNext() {
current < stop
}
override next() {
val ret = current
current = current + step
ret
}
override remove() {
throw new UnsupportedOperationException("Auto-generated function stub")
}
/**
* This is bad form. We could return a
* new RangeIterable here, but that seems worse.
*/
override iterator() {
this
}
}
The exact replacement for
for(int i = 0; i < 3; i++){
println("row ");
}
is
for (i : 0 ..< 3) {
println("row ")
}
Notice the exclusive range operator: ..<
Also you can doing it more idiomatically with
(1..3).forEach[println("row")]
Very new to Xtend but man it makes programming on the jvm awesome.
To me a range-based forEach implies the range is somehow meaningful. For looping a specific number of times with no iteration variable, I find Ruby's times loop expresses the intent more clearly:
3.times [|println("row")]
Sadly it's not a part of IntegerExtensions, but the implementation is trivial:
def static times(int iterations, Runnable runnable) {
if (iterations < 0) throw new IllegalArgumentException(
'''Can't iterate negative («iterations») times.''')
for (i: 0 ..< iterations) runnable.run()
}
Heh, I found the answer a little while later:
for(i: 1..3) {
println("row ")
}
Since Xtend 2.6, we also support the "traditional" for-loop, just like in Java.
There is actually a version of forEach() that accepts a lambda with two parameters.
It is useful if you need to access the iteration index within the loop.
(10..12).forEach[ x, i | println('''element=«x» index=«i»''')]
prints:
element=10 index=0
element=11 index=1
element=12 index=2

Is my programming logic correct here?

const char IsPressed = 1; // 1
const char WasHeldDown = 2; // 10
const char IsFirstPress = 4; // 100
char* keystates[256];
Class::CalculateKeyStates()
{
for(int i = 0; i < 256; ++i)
{
if(this->IsDown(i))
{
keystates[i] |= IsPressed; // turn on
if(keystates[i] & WasHeldDown)
{
//keystates[i] |= IsFirstPress;
keystates[i] &= ~IsFirstPress; // turn off
}
else
{
keystates[i] |= WasHeldDown + IsFirstPress; // Turn on
}
}
else
{
keystates[i] = 0; // Turn ALL off
}
}
}
This function would be a member function of a class, Class. The other member function, IsDown, will return a true if the key in question is down and false if not.
Can you see any way of further improving this function?
Thanks
EDIT:
I will expand a bit as to what is done why. This is a modification of an bit of code that works through an array keyStates (which was a struct of three bools) setting IsPressed to false for all of the keys. then again setting Ispressed to the value of this->IsDown and then a third time looping through checking if the key had been held, if it has then its no longer the first press so set that to false. if it was not held down, then set first press to true and was held to true as well, so next time it is flagged as having been held.
EDIT2:
Added some comments to code and corrected one line
Personally, I would define the key-states as disjoint states and write a simple state-machine, thus:
enum keystate
{
inactive,
firstPress,
active
};
keystate keystates[256];
Class::CalculateKeyStates()
{
for (int i = 0; i < 256; ++i)
{
keystate &k = keystates[i];
switch (k)
{
inactive:
k = (isDown(i)) ? firstPress : inactive;
break;
firstPress:
k = (isDown(i)) ? active : inactive;
break;
active:
k = (isDown(i)) ? active : inactive;
break;
}
}
}
This is easier to extend, and easier to read if it gets any more complex.
You are always setting IsFirstPress if the key is down, which might not be what you want.
I'm not sure what you want to achieve with IsFirstPress, as the keystate cannot remember any previous presses anyways. If you want to mark with this bit, that it's the first time you recognized the key being down, then your logic is wrong in the corresponding if statement.
keystates[i] & WasHeldDown evaluates to true if you already set the bit WasHeldDown earlier for this keystate.
In that case, what you may want to do is actually remove the IsFirstPress bit by xor-ing it: keystates[i] ^= IsFirstPress

Redundant code constructs

The most egregiously redundant code construct I often see involves using the code sequence
if (condition)
return true;
else
return false;
instead of simply writing
return (condition);
I've seen this beginner error in all sorts of languages: from Pascal and C to PHP and Java. What other such constructs would you flag in a code review?
if (foo == true)
{
do stuff
}
I keep telling the developer that does that that it should be
if ((foo == true) == true)
{
do stuff
}
but he hasn't gotten the hint yet.
if (condition == true)
{
...
}
instead of
if (condition)
{
...
}
Edit:
or even worse and turning around the conditional test:
if (condition == false)
{
...
}
which is easily read as
if (condition) then ...
Using comments instead of source control:
-Commenting out or renaming functions instead of deleting them and trusting that source control can get them back for you if needed.
-Adding comments like "RWF Change" instead of just making the change and letting source control assign the blame.
Somewhere I’ve spotted this thing, which I find to be the pinnacle of boolean redundancy:
return (test == 1)? ((test == 0) ? 0 : 1) : ((test == 0) ? 0 : 1);
:-)
Redundant code is not in itself an error. But if you're really trying to save every character
return (condition);
is redundant too. You can write:
return condition;
Declaring separately from assignment in languages other than C:
int foo;
foo = GetFoo();
Returning uselessly at the end:
// stuff
return;
}
I once had a guy who repeatedly did this:
bool a;
bool b;
...
if (a == true)
b = true;
else
b = false;
void myfunction() {
if(condition) {
// Do some stuff
if(othercond) {
// Do more stuff
}
}
}
instead of
void myfunction() {
if(!condition)
return;
// Do some stuff
if(!othercond)
return;
// Do more stuff
}
Using .tostring on a string
Putting an exit statement as first statement in a function to disable the execution of that function, instead of one of the following options:
Completely removing the function
Commenting the function body
Keeping the function but deleting all the code
Using the exit as first statement makes it very hard to spot, you can easily read over it.
Fear of null (this also can lead to serious problems):
if (name != null)
person.Name = name;
Redundant if's (not using else):
if (!IsPostback)
{
// do something
}
if (IsPostback)
{
// do something else
}
Redundant checks (Split never returns null):
string[] words = sentence.Split(' ');
if (words != null)
More on checks (the second check is redundant if you are going to loop)
if (myArray != null && myArray.Length > 0)
foreach (string s in myArray)
And my favorite for ASP.NET: Scattered DataBinds all over the code in order to make the page render.
Copy paste redundancy:
if (x > 0)
{
// a lot of code to calculate z
y = x + z;
}
else
{
// a lot of code to calculate z
y = x - z;
}
instead of
if (x > 0)
y = x + CalcZ(x);
else
y = x - CalcZ(x);
or even better (or more obfuscated)
y = x + (x > 0 ? 1 : -1) * CalcZ(x)
Allocating elements on the heap instead of the stack.
{
char buff = malloc(1024);
/* ... */
free(buff);
}
instead of
{
char buff[1024];
/* ... */
}
or
{
struct foo *x = (struct foo *)malloc(sizeof(struct foo));
x->a = ...;
bar(x);
free(x);
}
instead of
{
struct foo x;
x.a = ...;
bar(&x);
}
The most common redundant code construct I see is code that is never called from anywhere in the program.
The other is design patterns used where there is no point in using them. For example, writing "new BobFactory().createBob()" everywhere, instead of just writing "new Bob()".
Deleting unused and unnecessary code can massively improve the quality of the system and the team's ability to maintain it. The benefits are often startling to teams who have never considered deleting unnecessary code from their system. I once performed a code review by sitting with a team and deleting over half the code in their project without changing the functionality of their system. I thought they'd be offended but they frequently asked me back for design advice and feedback after that.
I often run into the following:
function foo() {
if ( something ) {
return;
} else {
do_something();
}
}
But it doesn't help telling them that the else is useless here. It has to be either
function foo() {
if ( something ) {
return;
}
do_something();
}
or - depending on the length of checks that are done before do_something():
function foo() {
if ( !something ) {
do_something();
}
}
From nightmarish code reviews.....
char s[100];
followed by
memset(s,0,100);
followed by
s[strlen(s)] = 0;
with lots of nasty
if (strcmp(s, "1") == 0)
littered about the code.
Using an array when you want set behavior. You need to check everything to make sure its not in the array before you insert it, which makes your code longer and slower.
Redundant .ToString() invocations:
const int foo = 5;
Console.WriteLine("Number of Items: " + foo.ToString());
Unnecessary string formatting:
const int foo = 5;
Console.WriteLine("Number of Items: {0}", foo);

Resources