Plange


Why I Put const On The Right

Sure, my reasoning is a bit eccentric, but the C++ standard allows for the const keyword to appear on the left or right hand side of a symbol, and I'm not a fan. In const qualifying an int *, there are some interesting patterns.

int const * ptr;
        
const int * ptr;
        
int * const ptr;
        
const int * const ptr;
        
int const * const ptr;
        
In line 1, the novice reader might not guess correctly which part the const is applied to. Is the int constant, or is the * constant? The rule is: const applies to whatever is on its left. So in line one, the int is the const part. Line 2 is a bit odd because const has nothing to its left. If const is at the beginning of the line, it applies to the right. So, line 2 is synonymous with line 1. Lines 4 and 5 are also synonymous for the same reason. I've never liked the special case. For examples sake, a pointer to a pointer.

const int * const * const ptrPtr;
		
Two of the consts are going to apply left, and one right. Why not just have all of them apply the same?

int const * const * const ptrPtr;
        
Granted, this doesn't solve the problem of `int const *` being uneasy to guess, but I figure that you should avoid one meaning having two different syntactic representations. For consistency, I always put const on the right hand side of what I want to qualify.

copyright © Brent Lewis 2017