I usually just type it out however, and then format my entire project 100% perfectly and accurately within a few seconds by using my IDE's automatic functionality.
This works for all style formats, even custom ones (assuming people use a modern, functional IDE).
@IWishIKnew -- I wouldn't be so quick to make that claim. Often times, compilers may opt to generate a switch-like structure in the resulting object code from an if/elseif chain. Likewise the same may be said about a compiler generating a simple branch if a switch has few paths. I would suspect that switches are a little bit more tricky to get right with branch-prediction optimizations like simple branches are.
Optimizations are also often times compiler-specific. One compiler might spit out drastically different binary than another.
* Just to be clear, I make no claims at being an optimization guru. I have next to no experience in any assembler level object code other than x86 (that is to say, no experience from technology in the past 10 years).
also, switches only work the same as if chains if and only if each operator is ==. if you want to compare using < > <= then you would need to use if blocks. also, you can only use chars, ints, bools, and floats (i think. never tested it)
@Little Bobby Tables
No you cannot use floats, only integral values. Well you can use float but it will be turned into a int by taking away the decimal part
it depends. in the first one the i doesnt exist past the for statement. in the second it has a a longer scope. if you are going to be using it multiple times then the bottom, otherwise the first
What?! If compilers let you access i outside of the scope of for (int i = 0; i < 5; i++){} then never touch those compilers as it should go out of scope and not be accessible.
For example:
1 2 3 4 5 6
for(int i = 0; i < 5; i++)
{
std::cout << i << std::endl;
}
std::cout << i << std::endl; // should return a compile error for being out of scope
g++ -g -pg -std=c++11 -Wall -c "ex2_33.cpp" (in directory: /home/equinox/project/tests/src)
ex2_33.cpp: In function ‘int main()’:
ex2_33.cpp:22:23: error: ‘i’ was not declared in this scope
std::cout << "\n" << i << std::endl;
^
Compilation failed.
I was just wondering because my tutor told me that he usually prefers the second one.
I would view said tutor's advice with suspicion.
I generally use another form of loop when I must access the counter afterwards. If I have to access the value after the loop to find out what it was, the condition for continuing the loop obviously doesn't just depend on the counter's value.
Keep in mind: the tutors ae students themselves. You should call into question their credibility if they say somthing questionable. That doesn't mean that the tutor is wrong for prefering the latter example, but the latter example is somwhat..... un-conventional? In any case, I wouldn't declare the for-loop's variable outside of it unless I was doing somthing really special with it.