I use MSVC++ 2008 and 2010 and i am a little confused about auto formatting. When i write code like this :
if(true)
if(true)
{
}
if(true)
{
}
and then i push CTRL+F but nothing happens and last condition stays in place but it should be aligned on a level with first condition. Behavior changes to right way if i add semicolon after braces of second condition like that :
if(true)
if(true)
{
};
if(true)
{
}
So the question is, is it right to add semicolon after condition according to C++ standard or it's just incorrect behavior of MSVC++?
That semicolon is completely superfluous. Looks like you've found a bug in Visual Studio.
Related
im a beginner starting to learn c++ i have a question.. Can i write scripts in do while loop i mean like this...
//you type do then like
do{
// your code here
}while(condition{ // <-- the question is here
then the code of the script
} ) closing Parenthesis and curly braces
yeah if you didn't understand that my question was that can i expand my condition in the while Parenthesis?? please answer because I'm learning C++ and I wanna improve.
The while condition takes an expression. That includes things like variables (foo), operators (1 + 2), and function calls. But it excludes things like if statements and additional loops. If you need to do something complicated inside of a while block, you should put it in a function.
do {
// ...
} while (should_continue(foo, bar));
bool should_continue(int foo, int bar) {
// ... complicated code goes here ...
}
Technically speaking, in C++11 and onward, you can create and evaluate a lambda in the same line, allowing arbitrary statements in expression context, but this is not very readable and should generally be a sign that your code needs to be split up into more functions.
// Don't do this; your coworkers will despise you.
do {
// ...
} while (([&]() {
// ... complicated code goes here ...
})());
Some non-portable compiler extensions will also allow the syntax you suggested in the question, where you can just throw braces { ... } with arbitrary statements in expression context. But, again, this is non-portable and not very readable code to begin with. So just write a function.
I am trying to understand a source code and i cannot figure out how the line for(;Q.size();) is meant to work. Could someone please simplify it for me ?
A for statement consists of three parts, separated by semicolons:
an init-statement
a condition
an iteration_expression
A for loop is equivalent to this code:
{
init_statement
while ( condition ) {
statement
iteration_expression ;
}
}
The init-statement and iteration_expression can be empty, but the semicolons between them are still required.
In your example, for(;Q.size();) would thus be equivalent to:
{
while ( Q.size() ) {
statement
}
}
Look at it this way:
for(<do nothing>;Q.size();<do nothing>) {//do something}
Now read the definition of the for loop and see that it fits perfectly.
As mentioned by others, essentially this becomes equivalent to while(Q.size())
It's a for loop which doesn't care about an incrementing index variable. As Blaze pointed out it's equivalent to a while loop.
for(;Q.size();)
{
// do something while Q is not empty
}
or equivalently
while(Q.size())
{
// do something while Q is not empty
}
In the following code example - is it bad practice? Also why does the compiler go into the 2nd bracketed statement? I've oddly never experienced this before but it came up in an interview situation. I would have thought the 2nd bracketed segment would look for another conditional statement. The code is as follows:
if ( condition )
{
// some code
}
{
// some code
}
Thank you for any helpful explanations in advance.
You can make a block using { and } anywhere; it does not need to be attached to an if condition.
It can be useful for controlling an object's lifetime.
{
MyObject foo;
// ... do something with foo ...
} // MyObject just went out of scope, so its destructor is called
// foo is no longer defined
if ( condition )
{
// gets executed if condition == TRUE
}
{
// always gets executed, has nothing to do with previous if statement
int a = 42 ; //only exists inside brackets
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
Why is the do while(false) necessary in the macros below?
#define LOG(message, ...) \
do { \
Lock<MutualExclusion> lock (logMutex); \
.... a lot of code ...
} while (false)
I dont think it serves any functional purpose. Am I overlooking something?
It turns a block into a single statement. If you just use a block (i.e. code enclosed in {}) strange things can happen, for example
#define STUFF() \
{ do_something(); do_something_else(); }
if (cond)
STUFF();
else
//...
the extra semi-colon breaks the syntax. The do {} while(false) instead is a single statement.
You can find more about this and other macro tricks here.
So you are forced to add semicolon at the end of the macro, when you use it. This is a common idiom and only way to enforce it.
If somebody has code that does this:
if (something)
LOG("My log message");
That would expand to:
if (something)
Lock<MutualExclusion> lock (logMutex);
// A bunch of other code
Which is incorrect (only the first line would be under the if statement).
The macro makes sure that the macro call is inside of a block of code.
People use it because otherwise, you can screw up your ifs with compound statements. Imagine
#define hai int x; \
x = 0;
if (condition)
hai;
else
func();
Imagine what the preprocessed source looks like.
if (condition)
int x;
x = 0;
else
func();
Oh wait- now our else doesn't work.
Macros like that however are typically unnecessary in C++.
The reason for this weird practice in #define's is to encapsulate the different assignments within a loop that is executed exactly once, so one may use the macro like a function. For example, with the code you posted, one can write:
if(...)
LOG(x, y);
else
// Something else
and it is expanded as
if(...)
do {...} while(false);
else
// Something else
This would not work without the do...while(false) surrounding the different assignments, because that would be expanded as
if(...)
Lock<MutualExclusion> lock (logMutex);
// Other code... Outside the if statement!
Also forcing a semicolon after the macro makes it look like a function and you wont get errors because you added an semicolon like after a normal function.
It provides local scope to that which is inside the macro.
It looks to me like it is only used for scoping rules, so that Lock<MutualExclusion> falls out of scope at the end of the block.
If that's the reason for it, then it's completely unnecesarry:
// some other code...
string s = "oh hai";
{
Lock<MutualExclusion> lock(logMutex);
// MAGIC HAPPENS
}
s = "oh bai";
In C++ you can initialize a variable in an if statement, like so:
if (CThing* pThing = GetThing())
{
}
Why would one consider this bad or good style? What are the benefits and disadvantages?
Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally when it is NULL. However, i don't like that you can't do this:
if (CThing* pThing = GetThing() && pThing->IsReallySomeThing())
{
}
If there's a way to make the above work, please post. But if that's just not possible, i'd still like to know why.
Question borrowed from here, similar topic but PHP.
The important thing is that a declaration in C++ is not an expression.
bool a = (CThing* pThing = GetThing()); // not legit!!
You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration.
if(A *a = new A)
{
// this is legit and a is scoped here
}
How can we know whether a is defined between one term and another in an expression?
if((A *a = new A) && a->test())
{
// was a really declared before a->test?
}
Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit:
if (CThing* pThing = GetThing())
{
if(pThing->IsReallySomeThing())
{
}
}
About the advantages:
It's always recommended to define variables when you first need them, not a line before. This is for improved readability of your code, since one can tell what CThing is without scrolling and searching where it was defined.
Also reducing scope to a loop/if block, causes the variable to be unreferenced after the execution of the code block, which makes it a candidate for Garbage Collection (if the language supports this feature).
if (CThing* pThing = GetThing())
It is bad style, because inside the if you are not providing a boolean expression. You are providing a CThing*.
CThing* pThing = GetThing();
if (pThing != NULL)
This is good style.
You can have initialization statements inside if and switch since C++17.
Your code would now be:
if (CThing* pThing = GetThing(); pThing->IsReallySomeThing())
{
// use pThing here
}
// pThing is out of scope here
One reason I don't normally do that is because of the common bug from a missed '=' in a conditional test. I use lint with the error/warnings set to catch those. It will then yell about all assignments inside conditionals.
Just an FYI some of the older Microsoft C++ compliers(Visual Studios 6, and .NET 2003 I think) don't quite follow the scoping rule in some instances.
for(int i = 0; i > 20; i++) {
// some code
}
cout << i << endl;
I should be out of scope, but that was/is valid code. I believe it was played off as a feature, but in my opinion it's just non compliance. Not adhering to the standards is bad. Just as a web developer about IE and Firefox.
Can someone with VS check and see if that's still valid?
This shoulddoesn't work in C++ sinceeven though it supports short circuiting evaluation. MaybeDon't try the following:
if ((CThing* pThing = GetThing()) && (pThing->IsReallySomeThing()))
{
}
err.. see Wesley Tarle's answer
So many things. First of all, bare pointers. Please avoid them by all means. Use references, optional, unique_ptr, shared_ptr. As the last resort, write your own class that deals with pointer ownership and nothing else.
Use uniform initialization if you can require C++11 (C++14 preferred to avoid C++11 defects): - it avoids = vs == confusion and it's stricter at checking the arguments if there are any.
if (CThing thing {})
{
}
Make sure to implement operator bool to get predictable conversion from CThing to bool. However, keep in mind that other people reading the code would not see operator bool right away. Explicit method calls are generally more readable and reassuring. If you can require C++17, use initializer syntax.
if (CThing thing {}; thing.is_good())
{
}
If C++17 is not an option, use a declaration above if as others have suggested.
{
CThing thing {};
if (thing.is_good())
{
}
}
You can also enclose the assignment in an extra set of ( ) to prevent the warning message.
I see that as kind of dangerous. The code below is much safer and the enclosing braces will still limit the scope of pThing in the way you want.
I'm assuming GetThing() sometimes returns NULL which is why I put that funny clause in the if() statement. It prevents IsReallySomething() being called on a NULL pointer.
{
CThing *pThing = GetThing();
if(pThing ? pThing->IsReallySomeThing() : false)
{
// Do whatever
}
}
also notice that if you're writing C++ code you want to make the compiler warning about "=" in a conditional statement (that isn't part of a declaration) an error.
It's acceptable and good coding practice. However, people who don't come from a low-level coding background would probably disagree.