How do I identify a variable name in a piece of code - regex

I am trying to write a halstead complexity measure in X++ (language isn't important) and I think the best way of doing this is by using regex on the source.
I have managed to do 90% of it but am struggling on variable names.
How do I identify a variable name in a piece of code.
Given the following piece of code
public void main()
{
int a, b, c, av;
className class;
strFmt("%1 %2 %3", a, b, c);
av = (a + b + c) / 3;
info("avg = %1");*/
if(a)
{
a++;
class.add(a);
}
else
{
b++;
class.subtract(b)
}
this.main();
}
I expect to be returned "a" "b" "c" "av" "class"
With the halstead it needs to count the instances of them. The way I was thinking is by storing the above in a list and then using whatever is in the list in a regex query. Catering for all possible uses of a variable would be insane.

I think you would have to reflect on the AOT in order to get the different variables.
You could use reflection with TreeNode or maybe you could use the XPPCompiler to get info on the objects you're processing to help:
info(strFmt("%1", new xppCompiler().dumpClass('salesformletter')));

This question made me sort of curious about how to do this and I came across this great post that has a custom AX tool to measure complexity plus a 175 page grad paper written about it.
http://bojanjovicic.com/complexity-tool-dynamics-ax-2009/
I'm experimenting with it now and looking how I can build onto it.

I'm back with the actual answer! Use the SysScannerClass and TreeNode object to correctly parse the code. Here's a beautiful sample I wrote that should make it cake.
static void JobParseSourceCode(Args _args)
{
TreeNode treeNode = TreeNode::findNode(#'\Data Dictionary\Tables\SalesTable\Methods\find');
SysScannerClass sysScannerClass = new SysScannerClass(treeNode);
int symbol;
int curLine;
str lineStr;
setPrefix("Scanning " + treeNode.treeNodePath());
for (symbol = sysScannerClass.firstSymbol(); symbol; symbol = sysScannerClass.nextSymbol())
{
if (curLine != sysScannerClass.line())
{
curLine = sysScannerClass.line();
lineStr = sysScannerClass.sourceLine(curLine);
}
// NOTE: symbol corresponds to macros in #TokenTypes
info(strFmt("Line %1: %2\t(Col %3): '%4' - MacroValue: %5, [%6]", curLine, lineStr, sysScannerClass.col(), sysScannerClass.strValue(), symbol, xppScanner::symbolClass(symbol)));
}
}

Well, the example does not quite qualify as X++ source, because class is a reserved word and cannot be used for a variable name.
Besides that a crude search for [a-zA-Z_][a-zA-Z_0-9]+ would give you all strings which could be a variable name. But without a full parser you would have trouble determining whether it is a keyword, class name, table name et cetera or a genuine variable name.
You could also use TextBuffer to tokenize your source:
static void TokenTest(Args _args)
{
str src = #'
public void main()
{
int a = 7, b = 11, c = 13, av;
info(strFmt("%1 %2 %3", a, b, c));
av = (a + b + c) / 3;
info(strFmt("avg = %1"));
this.main();
}
';
TextBuffer t = new TextBuffer();
t.ignoreCase(true);
t.setText(src); // Set the text to break in to tokens
while (t.nextToken(false,' (){}.,:;!=+-*/\n')) // The delimiters to search
{
info(t.token());
}
}
This will not work with strings and comments of course.
There is even an undocumented Keywords kernel class to play with!
Maybe the best choice would be to integrate with the cross reference tool, it has done the splitting for you!
I am afraid your remaining 10% may take 90% of your time!

You can use regex101.com to play with regex. I think you can play with the look-ahead (?=...) and the look-behind(?<=...) groups:
This regex will match all your variables:
/(?!void)(?<=[ \(])[a-z]+(?=[, ;+*\/\)])/
And here the proof:
http://regex101.com/r/hS9dQ6/2

I ended up cheating with the solution. I had already got all of the operators information such as int/public/methods etc... so I just used substituion on the source and then ran the following regex which found me the operands for the metric.
'_?\w+(?=([^"]*"[^"]*")*[^"]*$)|".+"'
There were some really good answers on here so I am going to look into using a hybrid of them to improve the implementation at a later date but for now we are getting the information we need and it seems to work for all cases we have tested it on.
If anyone is interested the regex I used for the operators is the following
(?i)\(|\{|\w+(?=(\(|:|\.))|\w+(?=\s\w)|(break|continue|return|true|false|retry|asc|breakpoint|desc|null|pause|throw|ttsAbort|ttsBegin|ttsCommit)(?=;)|((try|catch|else|by|do)(?=\n))|(\+=|-=|>=|<=|==|!=|=|\+\+|--|<<|>>|&&|\|\||\*|\/|\+|-|~|&|\^|\||>|<|!|\?|::|:|\.)+(?=([^"]*"[^"]*")*[^"]*$)
It has all the reserved keywords which are not covered by the first 4 statements, I also got the list of operators which x++ use.
It will need some modification to be used in other languages but considering other languages have better ways of dealing with these things you probably don't need it.
Thanks for all your answers

Related

How to print the name of a variable with parameters?

I would like to print : table_name[variable_value]
by giving ONE input : table_name[variable_name]
Let me explain a simpler case with a toy solution based on a macro:
int i = 1771;
I can print the variable_name with
#define toy_solution(x) cout << #x ;
If I execute
toy_solution(i);
"i" will be printed.
Now, imagine there is a well-allocated table T.
I would like to write in the program:
solution(T[i]);
and to read on the screen "T[1771]".
An ideal solution would treat the two cases, that is :
ideal_solution(i) would print i.
ideal_solution(T[i]) would print T[1771].
It is not important to me to use a macro or a function.
Thanks for your help.
#define toy_solution(x, i) cout << #x << "[" << i << "]"
I would like to print : table_name[variable_value]
by giving ONE input : table_name[variable_name]
well, as you did not understand my comment, I'll say out loud in an answer:
what you want to do is not possible
You have to choose between either #Alin's solution or #lizusek.
I think that #lizusek's solution is better because you're writing C++ code, so if you can do something that gives the same result than with using macros, you should use plain C++ code.
edit: let my try to explain why this is not possible
so what you want is:
f(T[i]) -> T, i
The only way you could write that so it would make sense in preprocessor is:
#define f(T[i]) cout<<#T#<<#i#
but then the preprocessor will give an error, because you can't index an array as a function (even a macro function) parameter:
test.c:5:12: error: expected comma in macro parameter list
#define f(T[i]) cout<<#T#<<#i#
^
If you try to do the same thing using a C++ function, then it's even more non-sense, as a function call such as:
toy_solution(t[i]);
would actually be translated to the value t[i] points to at runtime, so inside the function you'll never be able to known that the given value was actually in an array. So what you want is wrong, and you should stick to good coding practices: using a function and if what you want is:
toy_solution(t[i]);
then use:
toy_solution("t", i);
Possible solutions that you should never use
well, when I say it's not possible, it's that the only solutions I can think off are so twisted that you'd be insane to actually use them in your code… And if you do, I hope I'll never read one of your code or I may become violent :-) That's why I won't show you how or give you any code that could help do what I'm about to tell you.
use a template system
You could either write your code using your own template system or use one commonly used for HTML processing to process your source code through it and apply a transformation rule such as:
toy_solution(t[i]) -> toy_solution("t", t[i])
it's definitely possible, but it makes your build chain even more complicated and dependant on more tools. C/C++ build toolchain are complicated enough, please don't make it worst.
Or you code make your own fork of C and of a C compiler to change the syntax rules so what you want becomes possible. Though, I personnally would never use your fork, and then I'd go trolling and flaming about this on HN, deeply regretting to have given you such a bad idea :-)
use a custom class to encapsulate your arrays in
if you do something like:
template<T>
class Element {
T value;
List<T> _owner;
[…]
}
template<T>
class List {
Element<T> values[];
std::string _name;
[…]
}
so that when you call the function
toy_solution(T[i]);
the implementation would look like:
void toy_solution(Element<T> e) {
std::cout<<e.get_list_name()<<" "<<e.get_value()<<std::endl;
}
but that's sooo much boilerplate and overhead just to avoid doing a simple function definition that does not look as nice as you dream of, that I find it really stupid to do so.
You can write a function as simple as that:
void solution( std::string const& t, int i) {
std::cout << t << "[" << i << "]";
}
usage:
int i = 1771;
solution( "T", i);
You can also write a macro, but be aware that this is not type safe. Function should be preferred.

How to build a recursive descent parser

I've been working on a recursive descent parser for a simple calculator. When something is declared it is either declared as an int or a float. Currently I am saving the strings into two different vectors one for int and one for float. At this point I don't care what the numbers associated are I simply care that the string is declared before it is used.
My issue is that I have to be able to output a warning message if an int and float are being used in an operation such as float + int.
So if expression is term+expression or term-expression or term. In recursive descent how could I possibly check to see if an int is being used in an operation with a float. Sorry if the explanation is not clear. I'm finding it a bit difficult to explain. I have add some code if necessarily, I just didn't want to flood the question with code.
edit:
there is still a bunch of code missing, I figured just grab the important part, but I can upload the entire thing if need-be. I see some people didn't understand what the main question was. One of the requirements is "When integer and float values are mixed in +, -, * and /, the integer is converted to a float. print a message indicating the line number and that a conversion would be required." At the moment the program reads from a file. if you say "int x;" the program will currently save x in the int vector, then when you say something such as x=5; it will acknowledge that x has been declared and the assignment will pass. my issue is where if you say int x; float y; int z; x=5; y=7.5; z=x+y; how would I be able to check for that as at the moment my program only saves the type for variables and not the value. Essentially I'm wondering if it would be possible to do something like scan the completed parse as if it was a string or some other method of finding out of an operation using int and float is being done.
the lex scanner was created with flex
class Token {
Tokentype type;
string value;
int linenum;
public:
Token(Tokentype t, string v="") {
type = t;
value = v;
}
Tokentype getType() { return type; }
string getValue() { return value; }
int getLinenum() { return linenum; }
};
vector<string> int_list;
vector<string> float_list;
class PTree {
PTreeNodetype type;
PTree *left;
PTree *right;
public:
PTree(PTreeNodetype t, PTree *l=0, PTree *r=0) {
type = t;
left = l;
right = r;
}
PTreeNodetype getType(){ return type;}
};
// expr ::= term PLUS expr | term MINUS expr | term
PTree *
Expr() {
PTree *term = Term();
Token *t;
if (!term)
return 0;
t = getToken();
if (t == NULL){
delete t;
return 0;
}
if(t->getType() != T_SC)
{
if (t->getType() == T_RPAREN){
pushbacktoken(t);
return new PTree(EXPR, term);
}
if (t->getType() != T_PLUS && t->getType() != T_MINUS)
{
cout << t->getLinenum() << ":" << "Error: expected + or -" << endl;
pushbacktoken(t);
delete t;
return 0;
}
delete t;
PTree *expr = Expr();
if (!expr)
return 0;
return new PTree(EXPR, term, expr);
}
pushbacktoken(t);
return new PTree(EXPR, term);
}
I think you need to explain the structure of your code a little more.
In an interpreter like you are talking about normally there are three things going on:
A lexer/scanner is generating a token stream
A parser is taking the token and building semantic objects
A interpreter is consuming the semantic object tree and executing them
Stage 1 doesn't need to care that you are adding an int and a float. Stage 2 can populate an a warning field in your semantic object/struct that interpreter will print when it sees populated or the interpreter can recognize this warning condition itself.
To provide you any more detail or use more specific terminology we would need to see how you are representing operations.
Two options that I see, depending on what you are doing.
First. Don't worry about it while you are building the parse tree. Later, when you walk the tree, you can easily check this and throw an error.
Second. Use different rules for int and float. So you would have a rule for adding two ints and a rule for adding two floats. This also means you wouldn't have a number rule, which I am guessing you do, that mixes both ints and floats.
I definitely recommend the first way.
Calculators don't traditionally "declare" things, so its unclear what your calcualtor knows when it is parsing an expression.
If I assume that you "declare i int, r real" before the expression "i*r" is parsed, you seem to have several questions:
a) how do you know as you parse whether i and r have been declared? The technical answer is that during parsing you don't have to know; you can parse, build up a tree, and do such checking later. On a practical level, people often weave symbol lookups into the parsing process (this gets messier as your language gets bigger, so it isn't recommended for other than calculators [you'll discover that most C compilers do this, adding to their messiness]). The answer is easy: keep a list of defined symbol strings around, and when you encounter an identifier, look to see if its in the list.
b) how do you know the type of "i" or "r"? Easy. Associate with the symbol string, the declared type, e.g., , . Associated sets of declarations are commonly called symbol tables.
c) how do you know if operations are operating on the same ("the right") kind of values? Here you need to associate with every operand, its "type". Constants have obvious type; 1.0 is real, 1 is integer. "i" is integer, and your parser knows it because it looked up the type (above); similarly for "r". Each expression term then has to check its operands for compatibility. What might not be obvious is that each expression has to compute it result type, e.g., 3 * 4.0 is real, not integer. So in parallel to the parsing machinery, you need to propagate a type.
+1 to voidlogic. His answer should give you a basic idea of how to build a recursive descent parser. If you are having trouble with a certain part of yours, it would be nice to get a little more detail about how you are structuring your code.
If you would like to see an example of one, look at this implementation.
Here is a book that may help:
Compilers: Principles, Techniques and Tools ("Dragon Book") by A. Aho, M. Lam and R. Sethi.
Here is a set of tools that may help you:
GNU flex
GNU bison

good practice - similarly named variables

Trivial issue, but comes up a lot for me, and I imagine others too. Does anybody have a really good, really clever solution?
void some_function (obj &A, obj &B)
{
// do stuff with A...
//e.g.
double number_A = (value - A.member_func() ) * A.other_func();
// do stuff with B. similar BUT NOT EXACTLY like A...
//e.g.
double number_B = (value + B.member_func() ) * A.other_func();
// !!!!
// Big time TYPO - should say "B.other_func()", not "A.other_func()" !!!!
// !!!!
}
Any good guards against these types of errors?
I often have to work on two analogous variables, say one named version "A" and the other "B".
Because the code for each one is similar, I often use the code that worked on "A" as a "template" (i.e. copy & paste) for the code that works on "B" - making the small adjustments so that the code becomes appropriate for B.
Becuase I am human, I sometimes forget to change "A" to "B" in certain locations when copying the code. If I am lucky, this will cause the program to crash. Either way, this is disastrous.
Does anybody know any clever tricks for preventing such typos?
I've thought of...
enclosing brackets { } to try to restrict the scope of variables - but if objects A and B are in the function arguments, then this doesn't solve it.
dividing every function into sub-functions - one for A and one for B. This is a bit cumbersome from the developer perspective (passing/returning many of variables).
work only with pointers to the objects themselves - not the actual objects. This way we can { scope-control } the pointers. Also cumbersome, (and the overhead for defining a pointer is negligible, even if I call the function very, very often, right?)
In the example you give, the best defence is to do as little as possible in each function:
void some_function (obj &A, obj &B)
{
double number_A = do_stuff(A);
double number_B = do_similar_stuff(B);
}
double do_stuff(obj &A) {
return (value - A.member_func() ) * A.other_func();
}
// EITHER
double do_similar_stuff(obj &A) {
// no variable rename when copying == no problem
return value + A.member_func() ) * A.other_func();
}
// OR
double do_similar_stuff(obj &B) {
// A not in scope == very brief problem until compiler tells us
return value + B.member_func() ) * A.other_func();
// Beware, also, the nightmare scenario that there's some *other*
// `A` in scope, so this *still* compiles. For that reason, prefer
// the other option unless there's some good reason why this parameter
// should be `B`, and don't name member function parameters the same
// as data members etc.
}
Alternatively, you could make the relation between the two kinds of "stuff" explicit. Assuming that the unmatched parenthesis in your B code is supposed to go in the same place as the A. It all depends whether there really is a logical relationship between the two similar-looking operations:
void some_function (obj &A, obj &B)
{
double number_A = do_stuff(A, true);
double number_B = do_stuff(B, false);
}
double do_stuff(obj &A, bool subtract) {
// yeah, never call variables "tmp". Unless you have no context
// to give them meaning.
// Depending on the type of `tmp`, there might be a better way to
// write this, using multiplication by -1. But let's not assume, we'll do
// one refactor at a time.
auto tmp = subtract ? value - A.member_func() : value + A.member_func();
return tmp * A.other_func();
}
Other examples will vary. As you say it can be tiresome to write, but it has a number of benefits other than catching this error. Not least is that it will direct you towards writing your code in a way that you try to avoid passing/returning many variables. As a consequence, each line of your code affects fewer other things in the program, which is basic code hygiene.
It may also mean you can test that your formula with A is correct independently of whether your formula with B is correct, and sundry other benefits of short functions.
I have a few ideas in mind
you could use snippets if your editor supports them or move to an editor/ide which has support for them (personally I use kdevelop and snippets are very useful as they replace all occurences of a snippet variable)
you could also use refactoring (in a separate function if you
already used the names this one)
also selecting a piece of code and doing replace all in selection
might help
using defines is also an option
Still, going with a smarter IDE is the best in my opinion.
I think your best bet is not have similar function names in other classes. Also, having unit tests coupled with peer code reviews should catch these errors most of the time. However, there have been many times in SW history where these types of errors are never caught until many days, months, or years later.

In which case is if(a=b) a good idea? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Inadvertent use of = instead of ==
C++ compilers let you know via warnings that you wrote,
if( a = b ) { //...
And that it might be a mistake that you certainly wanted to write:
if( a == b ) { //...
But is there a case where the warning should be ignored, because it's a good way to use this "feature"?
I don't see any code clarity reason possible, so is there a case where it’s useful?
Two possible reasons:
Assign & Check
The = operator (when not overriden) normally returns the value that it assigned. This is to allow statements such as a=b=c=3. In the context of your question, it also allows you to do something like this:
bool global;//a global variable
//a function
int foo(bool x){
//assign the value of x to global
//if x is equal to true, return 4
if (global=x)
return 4;
//otherwise return 3
return 3;
}
...which is equivalent to but shorter than:
bool global;//a global variable
//a function
int foo(bool x){
//assign the value of x to global
global=x;
//if x is equal to true, return 4
if (global==true)
return 4;
//otherwise return 3
return 3;
}
Also, it should be noted (as stated by Billy ONeal in a comment below) that this can also work when the left-hand argument of the = operator is actually a class with a conversion operator specified for a type which can be coerced (implicitly converted) to a bool. In other words, (a=b) will evaulate to true or false if a is of a type which can be coerced to a boolean value.
So the following is a similar situation to the above, except the left-hand argument to = is an object and not a bool:
#include <iostream>
using namespace std;
class Foo {
public:
operator bool (){ return true; }
Foo(){}
};
int main(){
Foo a;
Foo b;
if (a=b)
cout<<"true";
else
cout<<"false";
}
//output: true
Note: At the time of this writing, the code formatting above is bugged. My code (check the source) actually features proper indenting, shift operators and line spacing. The <'s are supposed to be <'s, and there aren't supposed to be enourmous gaps between each line.
Overridden = operator
Since C++ allows the overriding of operators, sometimes = will be overriden to do something other than what it does with primitive types. In these cases, the performing the = operation on an object could return a boolean (if that's how the = operator was overridden for that object type).
So the following code would perform the = operation on a with b as an argument. Then it would conditionally execute some code depending on the return value of that operation:
if (a=b){
//execute some code
}
Here, a would have to be an object and b would be of the correct type as defined by the overriding of the = operator for objects of a's type. To learn more about operator overriding, see this wikipedia article which includes C++ examples: Wikipedia article on operator overriding
while ( (line = readNextLine()) != EOF) {
processLine();
}
You could use to test if a function returned any error:
if (error_no = some_function(...)) {
// Handle error
}
Assuming that some_function returns the error code in case of an error. Or zero otherwise.
This is a consequence of basic feature of the C language:
The value of an assignment operation is the assigned value itself.
The fact that you can use that "return value" as the condition of an if() statement is incidental.
By the way, this is the same trick that allows this crazy conciseness:
void strcpy(char *s, char *t)
{
while( *s++ = *t++ );
}
Of course, the while exits when the nullchar in t is reached, but at the same time it is copied to the destination s string.
Whether it is a good idea, usually not, as it reduce code readability and is prone to errors.
Although the construct is perfectly legal syntax and your intent may truly be as shown below, don't leave the "!= 0" part out.
if( (a = b) != 0 ) {
...
}
The person looking at the code 6 months, 1 year, 5 years from now, at first glance, is simply going to believe the code contains a "classic bug" written by a junior programmer and will try to "fix" it. The construct above clearly indicates your intent and will be optimized out by the compiler. This would be especially embarrassing if you are that person.
Your other option is to heavily load it with comments. But the above is self-documenting code, which is better.
Lastly, my preference is to do this:
a = b;
if( a != 0 ) {
...
}
This is about a clear as the code can get. If there is a performance hit, it is virtually zero.
A common example where it is useful might be:
do {
...
} while (current = current->next);
I know that with this syntax you can avoid putting an extra line in your code, but I think it takes away some readability from the code.
This syntax is very useful for things like the one suggested by Steven Schlansker, but using it directly as a condition isn't a good idea.
This isn't actually a deliberate feature of C, but a consequence of two other features:
Assignment returns the assigned value
This is useful for performing multiple assignments, like a = b = 0, or loops like while ((n = getchar()) != EOF).
Numbers and pointers have truth values
C originally didn't have a bool type until the 1999 standard, so it used int to represent Boolean values. Backwards compatibility requires C and C++ to allow non-bool expressions in if, while, and for.
So, if a = b has a value and if is lenient about what values it accepts, then if (a = b) works. But I'd recommend using if ((a = b) != 0) instead to discourage anyone from "fixing" it.
You should explicitly write the checking statement in a better coding manner, avoiding the assign & check approach. Example:
if ((fp = fopen("filename.txt", "wt")) != NULL) {
// Do something with fp
}
void some( int b ) {
int a = 0;
if( a = b ) {
// or do something with a
// knowing that is not 0
}
// b remains the same
}
But is there a case where the warning
should be ignored because it's a good
way to use this "feature"? I don't see
any code clarity reason possible so is
there a case where its useful?
The warning can be suppressed by placing an extra parentheses around the assignment. That sort of clarifies the programmer's intent. Common cases I've seen that would match the (a = b) case directly would be something like:
if ( (a = expression_with_zero_for_failure) )
{
// do something with 'a' to avoid having to reevaluate
// 'expression_with_zero_for_failure' (might be a function call, e.g.)
}
else if ( (a = expression2_with_zero_for_failure) )
{
// do something with 'a' to avoid having to reevaluate
// 'expression2_with_zero_for_failure'
}
// etc.
As to whether writing this kind of code is useful enough to justify the common mistakes that beginners (and sometimes even professionals in their worst moments) encounter when using C++, it's difficult to say. It's a legacy inherited from C and Stroustrup and others contributing to the design of C++ might have gone a completely different, safer route had they not tried to make C++ backwards compatible with C as much as possible.
Personally I think it's not worth it. I work in a team and I've encountered this bug several times before. I would have been in favor of disallowing it (requiring parentheses or some other explicit syntax at least or else it's considered a build error) in exchange for lifting the burden of ever encountering these bugs.
while( (l = getline()) != EOF){
printf("%s\n", l);
}
This is of course the simplest example, and there are lots of times when this is useful. The primary thing to remember is that (a = true) returns true, just as (a = false) returns false.
Preamble
Note that this answer is about C++ (I started writing this answer before the tag "C" was added).
Still, after reading Jens Gustedt's comment, I realized it was not the first time I wrote this kind of answer. Truth is, this question is a duplicate of another, to which I gave the following answer:
Inadvertent use of = instead of ==
So, I'll shamelessly quote myself here to add an important information: if is not about comparison. It's about evaluation.
This difference is very important, because it means anything can be inside the parentheses of a if as long as it can be evaluated to a Boolean. And this is a good thing.
Now, limiting the language by forbidding =, where all other operators are authorized, is a dangerous exception for the language, an exception whose use would be far from certain, and whose drawbacks would be numerous indeed.
For those who are uneasy with the = typo, then there are solutions (see Alternatives below...).
About the valid uses of if(i = 0) [Quoted from myself]
The problem is that you're taking the problem upside down. The "if" notation is not about comparing two values like in some other languages.
The C/C++ if instruction waits for any expression that will evaluate to either a Boolean, or a null/non-null value. This expression can include two values comparison, and/or can be much more complex.
For example, you can have:
if(i >> 3)
{
std::cout << "i is less than 8" << std::endl
}
Which proves that, in C/C++, the if expression is not limited to == and =. Anything will do, as long as it can be evaluated as true or false (C++), or zero non-zero (C/C++).
About valid uses
Back to the non-quoted answer.
The following notation:
if(MyObject * p = findMyObject())
{
// uses p
}
enables the user to declare and then use p inside the if. It is a syntactic sugar... But an interesting one. For example, imagine the case of an XML DOM-like object whose type is unknown well until runtime, and you need to use RTTI:
void foo(Node * p_p)
{
if(BodyNode * p = dynamic_cast<BodyNode *>(p_p))
{
// this is a <body> node
}
else if(SpanNode * p = dynamic_cast<SpanNode *>(p_p))
{
// this is a <span> node
}
else if(DivNode * p = dynamic_cast<DivNode *>(p_p))
{
// this is a <div> node
}
// etc.
}
RTTI should not be abused, of course, but this is but one example of this syntactic sugar.
Another use would be to use what is called C++ variable injection. In Java, there is this cool keyword:
synchronized(p)
{
// Now, the Java code is synchronized using p as a mutex
}
In C++, you can do it, too. I don't have the exact code in mind (nor the exact Dr. Dobb's Journal's article where I discovered it), but this simple define should be enough for demonstration purposes:
#define synchronized(lock) \
if (auto_lock lock_##__LINE__(lock))
synchronized(p)
{
// Now, the C++ code is synchronized using p as a mutex
}
(Note that this macro is quite primitive, and should not be used as is in production code. The real macro uses a if and a for. See sources below for a more correct implementation).
This is the same way, mixing injection with if and for declaration, you can declare a primitive foreach macro (if you want an industrial-strength foreach, use Boost's).
About your typo problem
Your problem is a typo, and there are multiple ways to limit its frequency in your code. The most important one is to make sure the left-hand-side operand is constant.
For example, this code won't compile for multiple reasons:
if( NULL = b ) // won't compile because it is illegal
// to assign a value to r-values.
Or even better:
const T a ;
// etc.
if( a = b ) // Won't compile because it is illegal
// to modify a constant object
This is why in my code, const is one of the most used keyword you'll find. Unless I really want to modify a variable, it is declared const and thus, the compiler protects me from most errors, including the typo error that motivated you to write this question.
But is there a case where the warning should be ignored because it's a good way to use this "feature"? I don't see any code clarity reason possible so is there a case where its useful?
Conclusion
As shown in the examples above, there are multiple valid uses for the feature you used in your question.
My own code is a magnitude cleaner and clearer since I use the code injection enabled by this feature:
void foo()
{
// some code
LOCK(mutex)
{
// some code protected by a mutex
}
FOREACH(char c, MyVectorOfChar)
{
// using 'c'
}
}
... which makes the rare times I was confronted to this typo a negligible price to pay (and I can't remember the last time I wrote this type without being caught by the compiler).
Interesting sources
I finally found the articles I've had read on variable injection. Here we go!!!
FOR_EACH and LOCK (2003-11-01)
Exception Safety Analysis (2003-12-01)
Concurrent Access Control & C++ (2004-01-01)
Alternatives
If one fears being victim of the =/== typo, then perhaps using a macro could help:
#define EQUALS ==
#define ARE_EQUALS(lhs,rhs) (lhs == rhs)
int main(int argc, char* argv[])
{
int a = 25 ;
double b = 25 ;
if(a EQUALS b)
std::cout << "equals" << std::endl ;
else
std::cout << "NOT equals" << std::endl ;
if(ARE_EQUALS(a, b))
std::cout << "equals" << std::endl ;
else
std::cout << "NOT equals" << std::endl ;
return 0 ;
}
This way, one can protect oneself from the typo error, without needing a language limitation (that would cripple language), for a bug that happens rarely (i.e., almost never, as far as I remember it in my code).
There's an aspect of this that hasn't been mentioned: C doesn't prevent you from doing anything it doesn't have to. It doesn't prevent you from doing it because C's job is to give you enough rope to hang yourself by. To not think that it's smarter than you. And it's good at it.
Never!
The exceptions cited don't generate the compiler warning. In cases where the compiler generates the warning, it is never a good idea.
RegEx sample
RegEx r;
if(((r = new RegEx("\w*)).IsMatch()) {
// ... do something here
}
else if((r = new RegEx("\d*")).IsMatch()) {
// ... do something here
}
Assign a value test
int i = 0;
if((i = 1) == 1) {
// 1 is equal to i that was assigned to a int value 1
}
else {
// ?
}
My favourite is:
if (CComQIPtr<DerivedClassA> a = BaseClassPtr)
{
...
}
else if (CComQIPtr<DerivedClassB> b = BaseClassPtr)
{
...
}

Inadvertent use of = instead of ==

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
It seems that
if (x=y) { .... }
instead of
if (x==y) { ... }
is a root of many evils.
Why don't all compilers mark it as error instead of a configurable warning?
I'm interested in finding out cases where the construct if (x=y) is useful.
One useful construct is for example:
char *pBuffer;
if (pBuffer = malloc(100))
{
// Continue to work here
}
As mentioned before, and downvoted several times now, I might add this is not specially good style, but I have seen it often enough to say it's useful. I've also seen this with new, but it makes more pain in my chest.
Another example, and less controversial, might be:
while (pointer = getNextElement(context))
{
// Go for it. Use the pointer to the new segment of data.
}
which implies that the function getNextElement() returns NULL when there is no next element so that the loop is exited.
Most of the time, compilers try very hard to remain backward compatible.
Changing their behavior in this matter to throw errors will break existing legitimate code, and even starting to throw warnings about it will cause problems with automatic systems that keep track of code by automatically compiling it and checking for errors and warnings.
This is an evil we're pretty much stuck with at the moment, but there are ways to circumvent and reduce the dangers of it.
Example:
void *ptr = calloc(1, sizeof(array));
if (NULL = ptr) {
// Some error
}
This causes a compilation error.
Simple answer: An assignment operation, such as x=y, has a value, which is the same as the newly assigned value in x. You can use this directly in a comparison, so instead of
x = y; if (x) ...
you can write
if (x = y) ...
It is less code to write (and read), which is sometimes a good thing, but nowadays most people agree that it should be written in some other way to increase readability. For example, like this:
if ((x = y) != 0) ...
Here is a realistic example. Assume you want to allocate some memory with malloc, and see if it worked. It can be written step by step like this:
p = malloc(4711); if (p != NULL) printf("Ok!");
The comparison to NULL is redundant, so you can rewrite it like this:
p = malloc(4711); if (p) printf("Ok!");
But since the assignment operation has a value, which can be used, you could put the entire assignment in the if condition:
if (p = malloc(4711)) printf("Ok!");
This does the same thing, but it is more concise.
Because it's not illegal (in C or C++ anyway) and sometimes useful...
if ( (x = read(blah)) > 0)
{
// now you know how many bits/bytes/whatever were read
// and can use that info. Esp. if you know, say 30 bytes
// are coming but only got 10
}
Most compilers kick up a real stink if you don't put parenthesis around the assignment anyway, which I like.
About the valid uses of if(i = 0)
The problem is that you're taking the problem upside down. The "if" notation is not about comparing two values like in some other languages.
The C/C++ "if" instruction waits for any expression that will evaluate to either a boolean, or a null/non-null value. This expression can include two values comparison, and/or can be much more complex.
For example, you can have:
if(i >> 3)
{
std::cout << "i is less than 8" << std::endl
}
Which proves that, in C/C++, the if expression is not limited to == and =. Anything will do, as long as it can be evaluated as true or false (C++), or zero non-zero (C/C++).
Another C++ valid use:
if(MyObject * pObject = dynamic_cast<MyInterface *>(pInterface))
{
pObject->doSomething();
}
And these are simple uses of the if expression (note that this can be used, too, in the for loop declaration line). More complex uses do exist.
About advanced uses of if(i = 0) in C++ (Quoted from myself)
After discovering a duplicate of this question at In which case is if(a=b) a good idea?, I decided to complete this answer with an additional bonus, that is, variable injection into a scope, which is possible in C++, because if will evaluate its expression, including a variable declaration, instead of limiting itself to compare two operands like it is done in other languages:
So, quoting from myself:
Another use would be to use what is called C++ variable injection. In Java, there is this cool keyword:
synchronized(p)
{
// Now, the Java code is synchronized using p as a mutex
}
In C++, you can do it, too. I don't have the exact code in mind (nor the exact Dr. Dobb's Journal's article where I discovered it), but this simple define should be enough for demonstration purposes:
#define synchronized(lock) \
if (auto_lock lock_##__LINE__(lock))
synchronized(p)
{
// Now, the C++ code is synchronized using p as a mutex
}
This is the same way, mixing injection with an if and for declaration. You can declare a primitive foreach macro (if you want an industrial-strength foreach, use Boost's).
See the following articles for a less naive, more complete and more robust implementation:
FOR_EACH and LOCK
Exception Safety Analysis
Concurrent Access Control & C++
How many errors of this kind really happens?
Rarely. In fact, I have yet to remember one, and I have been a professional for the past 8 years.
I guess it happened, but then, in 8 years, I did produce a sizeable quantity of bugs. It's just that this kind of bugs did not happen enough to have me remember them in frustration.
In C, you'll have more bugs because of buffer overruns, like:
void doSomething(char * p)
{
strcpy(p, "Hello, World! How are you \?\n");
}
void doSomethingElse()
{
char buffer[16];
doSomething(buffer);
}
In fact, Microsoft was burned so hard because of that they added a warning in Visual C++ 2008 deprecating strcpy!
How can you avoid most errors?
The very first "protection" against this error is to "turn around" the expression: As you can't assign a value to a constant, this:
if(0 = p) // ERROR: It should have been if(0 == p). IT WON'T COMPILE!
It won't compile.
But I find this quite a poor solution, because it tries to hide behind a style what should be a general programming practice, that is: Any variable that is not supposed to change should be constant.
For example, instead of:
void doSomething(char * p)
{
if(p == NULL) // POSSIBLE TYPO ERROR
return;
size_t length = strlen(p);
if(length == 0) // POSSIBLE TYPO ERROR
printf("\"%s\" length is %i\n", p, length);
else
printf("the string is empty\n");
}
Trying to "const" as many variables as possible will make you avoid most typo errors, including those not inside "if" expressions:
void doSomething(const char * const p) // CONST ADDED HERE
{
if(p == NULL) // NO TYPO POSSIBLE
return;
const size_t length = strlen(p); // CONST ADDED HERE
if(length == 0) // NO TYPO POSSIBLE
printf("\"%s\" length is %i\n", p, length);
else
printf("the string is empty\n");
}
Of course, it is not always possible (as some variables do need to change), but I found than most of the variables I use are constants (I keep initializing them once, and then, only reading them).
Conclusion
Usually, I see code using the if(0 == p) notation, but without the const-notation.
To me, it's like having a trash can for recyclables, and another for non-recyclable, and then in the end, throw them together in the same container.
So, do not parrot an easy style habit hoping it will make your code a lot better. It won't. Use the language constructs as much as possible, which means, in this case, using both the if(0 == p) notation when available, and using of the const keyword as much as possible.
The 'if(0 = x)' idiom is next to useless because it doesn't help when both sides are variables ('if(x = y)') and most (all?) of the time you should be using constant variables rather than magic numbers.
Two other reasons I never use this idiom, IMHO it makes code less readable and to be honest I find the single '='to be the root of very little evil. If you test your code thouroughly (which we all do, obviously) this sort of syntax error turns up very quickly.
Standard C idiom for iterating:
list_elem* curr;
while ( (curr = next_item(list)) != null ) {
/* ... */
}
Many compilers will detect this and warn you, but only if you set the warning level high enough.
For example:
~> gcc -c -Wall foo.c
foo.c: In function ‘foo’:
foo.c:5: warning: suggest parentheses around assignment used as truth value
Is this really such a common error? I learned about it when I learned C myself, and as a teacher I have occasionally warned my students and told them that it is a common error, but I have rarely seen it in real code, even from beginners. Certainly not more often than other operator mistakes, such as for example writing "&&" instead of "||".
So the reason that compilers don't mark it as an error (except for it being perfectly valid code) is perhaps that it isn't the root of very many evils.
The assignment as conditional is legal C and C++, and any compiler that doesn't permit it isn't a real C or C++ compiler. I would hope that any modern language not designed to be explicitly compatible with C (as C++ was) would consider it an error.
There are cases where this allows concise expressions, such as the idiomatic while (*dest++ = *src++); to copy a string in C, but overall it's not very useful, and I consider it a mistake in language design. It is, in my experience, easy to make this mistake, and hard to spot when the compiler doesn't issue a warning.
I think the C and C++ language designers noticed there is no real use in forbidding it because
Compilers can warn about it if they want anyway
Disallowing it would add special cases to the language, and would remove a possible feature.
There isn't complexity involved in allowing it. C++ just says that an expression implicitly convertible to bool is required. In C, there are useful cases detailed by other answers. In C++, they go one step further and allowed this one in addition:
if(type * t = get_pointer()) {
// ....
}
Which actually limits the scope of t to only the if and its bodies.
It depends on the language. Java flags it as an error as only Boolean expressions can be used inside the if parenthesis (and unless the two variables are Boolean, in which case the assignment is also a Boolean).
In C, it is a quite common idiom for testing pointers returned by malloc or if after a fork we are in the parent or child process:
if ( x = (X*) malloc( sizeof(X) ) {
// 'malloc' worked, pointer != 0
if ( pid = fork() ) {
// Parent process as pid != 0
C/C++ compilers will warn with a high enough warning level if you ask for it, but it cannot be considered an error as the language allows it. Unless, then again, you ask the compiler to treat warnings as errors.
Whenever comparing with constants, some authors suggest using the test constant == variable so that the compiler will detect if the user forgets the second equality sign.
if ( 0 == variable ) {
// The compiler will complaint if you mistakenly
// write =, as you cannot assign to a constant
Anyway, you should try to compile with the highest possible warning settings.
Try viewing
if( life_is_good() )
enjoy_yourself();
as
if( tmp = life_is_good() )
enjoy_yourself();
Part of it has to do with personal style and habits. I am agnostic to reading either if (kConst == x) or if (x == kConst). I don't use the constant on the left because historically I don't make that error and I write code as I would say it or would like to read it. I see this as a personal decision as part of a personal responsibility to being a self-aware, improving engineer. For example, I started analyzing the types of bugs that I was creating and started to re-engineer my habits so as not to make them - similar to constant on the left, just with other things.
That said, compiler warnings, historically, are pretty crappy and even though this problem has been well known for years, I didn't see it in a production compiler until the late 80's. I also found that working on projects that were portable helped clean up my C a great deal, as different compilers and different tastes (ie, warnings) and different subtle semantic differences.
I, personally, consider this the most useful example.
Say that you have a function read() that returns the number of bytes read, and you need to use this in a loop. It's a lot simpler to use
while((count = read(foo)) > 0) {
//Do stuff
}
than to try and get the assignment out of the loop head, which would result in things like
while(1) {
count = read(foo);
if(!(count > 0))
break;
//...
}
or
count = read(foo);
while(count > 0) {
//...
count = read(foo);
}
The first construct feels awkward, and the second repeats code in an unpleasant way.
Unless, of course, I've missed some brilliant idiom for this...
There are a lot of great uses of the assignment operator in a conditional statement, and it'd be a royal pain in the ass to see warnings about each one all the time. What would be nice would be a function in your IDE that let you highlight all the places where assignment has been used instead of an equality check - or - after you write something like this:
if (x = y) {
then that line blinks a couple of times. Enough to let you know that you've done something not exactly standard, but not so much that it's annoying.
if ((k==1) || (k==2)) is a conditional
if ((k=1) || (k=2) ) is BOTH a conditional AND an assignment statement
Here's the explanation
Like most languages, C works inner-most to outermost in order by operator precedence.
First, it tries to set k to 1, and succeeds.
Result: k = 1 and Boolean = 'true'
Next: it sets k to 2, and succeeds.
Result: k = 2 and Boolean = 'true'
Next: it evaluates (true || true)
Result: k still = 2, and Boolean = true
Finally, it then resolves the conditional: If (true)
Result: k = 2 and the program takes the first branch.
In nearly 30 years of programming I have not seen a valid reason for using this construct, though if one exists it probably has to do with a need to deliberately obfuscate your code.
When one of our new people has a problem, this is one of the things I look for, right along with not sticking a terminator on a string, and copying a debug statement from one place to another and not changing the '%i to '%s' to match the new field they are dumping.
This is fairly common in our shop because we constantly switch between C and Oracle PL/SQL; if( k = 1) is the correct syntax in PL/SQL.
It is very common with "low level" loop constructs in C/C++, such as with copies:
void my_strcpy(char *dst, const char *src)
{
while((*dst++ = *src++) != '\0') { // Note the use of extra parentheses, and the explicit compare.
/* DO NOTHING */
}
}
Of course, assignments are very common with for loops:
int i;
for(i = 0; i < 42; ++i) {
printf("%d\n", i);
}
I do believe it is easier to read assignments when they are outside of if statements:
char *newstring = malloc(strlen(src) * sizeof(char));
if(newstring == NULL) {
fprintf(stderr, "Out of memory, d00d! Bailing!\n");
exit(2);
}
// Versus:
if((newstring = malloc(strlen(src) * sizeof(char))) == NULL) // ew...
Make sure the assignment is obvious, thuogh (as with the first two examples). Don't hide it.
As for accidental uses ... that doesn't happen to me much. A common safeguard is to put your variable (lvalues) on the right hand side of the comparison, but that doesn't work well with things like:
if(*src == *dst)
because both oprands to == are lvalues!
As for compilers ... who can blame 'em? Writing compilers is difficult, and you should be writing perfect programs for the compiler anyway (remember GIGO?). Some compilers (the most well-known for sure) provide built-in lint-style checking, but that certainly isn't required. Some browsers don't validate every byte of HTML and Javascript it's thrown, so why would compilers?
There are several tactics to help spot this .. one is ugly, the other is typically a macro. It really depends on how you read your spoken language (left to right, right to left).
For instance:
if ((fp = fopen("foo.txt", "r") == NULL))
Vs:
if (NULL == (fp = fopen(...)))
Sometimes it can be easier to read/write (first) what your testing for, which makes it easier to spot an assignment vs a test. Then bring in most comp.lang.c folks that hate this style with a passion.
So, we bring in assert():
#include <assert.h>
...
fp = fopen("foo.txt", "r");
assert(fp != NULL);
...
when your at the midst, or end of a convoluted set of conditionals, assert() is your friend. In this case, if FP == NULL, an abort() is raised and the line/file of the offending code is conveyed.
So if you oops:
if (i = foo)
insted of
if (i == foo)
followed by
assert (i > foo + 1)
... you'll quickly spot such mistakes.
Hope this helps :)
In short, reversing arguments sometimes helps when debugging .. assert() is your long life friend and can be turned off in compiler flags in production releases.
As pointed out in other answers, there are cases where using assignment within a condition offers a brief-but-readable piece of code that does what you want. Also, a lot of up-to-date compilers will warn you if they see an assignment where they expect a condition. (If you're a fan of the zero-warnings approach to development, you'll have seen these.)
One habit I've developed that keeps me from getting bitten by this (at least in C-ish languages) is that if one of the two values I'm comparing is a constant (or otherwise not a legal lvalue), I put it on the left-hand side of the comparator: if (5 == x) { whatever(); } Then, if I should accidentally type if (5 = x), the code won't compile.
You asked why it was useful, but keep questioning examples people are providing. It's useful because it's concise.
Yes, all the examples which use it can be rewritten - as longer pieces of code.
I have only had this typo once in my 15 years of development. I would not say it is on the top of my list of things to look out for. I also avoid that construct anyway.
Note also that some compilers (the one I use) issue a warning on that code. Warnings can be treated as errors for any compiler worth its salt. They can also be ignored.
Placing the constant on the left side of a comparison is defensive programming. Sure you would never make the silly mistake of forgetting that extra '=', but who knows about the other guy.
The D programming language does flag this as an error. To avoid the problem with wanting to use the value later, it allows declarations sort of like C++ allows with for loops.
if(int i = some_fn())
{
another_fn(i);
}
The compiler won't flag it as an error because it is valid C/C++. But what you can do (at least with Visual C++) is turn up the warning level so that it flags it as a warning and then tell the compiler to treat warnings as errors. This is a good practice anyway so that developers don't ignore warnings.
If you had actually meant = instead of == then you need to be more explicit about it. E.g.,
if ((x = y) != 0)
Theoretically, you're supposed to be able to do this:
if ((x = y))
to override the warning, but that doesn't seem to always work.
In practice I don't do it, but a good tip is to do:
if ( true == $x )
In the case that you leave out an equals, assigning $x to true will obviously return an error.
RegEx sample
RegEx r;
if(((r = new RegEx("\w*)).IsMatch()) {
// ... do something here
}
else if((r = new RegEx("\d*")).IsMatch()) {
// ... do something here
}
Assign a value test
int i = 0;
if((i = 1) == 1) {
// 1 is equal to i that was assigned to a int value 1
}
else {
// ?
}
That's why it's better to write:
0 == CurrentItem
Instead of:
CurrentItem == 0
so that the compiler warns you if you type = instead of ==.