47

You are comparing variable declarations to #defines, which is incorrect. With a #define, you create a mapping between an identifier and a snippet of source code. The C preprocessor will then literally substitute any occurrences of that identifier with the provided snippet. Writing #define FOO 40 + 2 int foos = FOO + FOO * FOO; ends up being the same thing ...


45

It's not a problem to define a variable within a loop. In fact, it's good practice, since identifiers should be confined to the smallest possible scope. What's bad is to assign a variable within a loop if you could just as well assign it once before the loop runs. Depending on how complex the right-hand side of the assignment is, this could become rather ...


39

A design constraint of the C language was that it was supposed to be compiled by a single-pass compiler, which makes it suitable for very memory-constrained systems. Therefore, the compiler knows at any point only about stuff that was mentioned before. The compiler can't skip forward in the source to find a function declaration and then go back to compile a ...


30

Because C is a single-pass, statically-typed, weakly-typed, compiled language. Single-pass means the compiler does not look ahead to see the definition of a function or variable. Since the compiler does not look ahead, the declaration of a function must come before the use of the function, otherwise the compiler does not know what its type signature is. ...


20

Complex types have non-trivial constructors and destructors. Those will get called at the start and end of the loop body (as it's initialized and goes out of scope). If the initialization is expensive like it needs to allocate some memory then that should be avoided. However for trivial types that is no problem. The allocation and deallocation itself is ...


10

First, you programs are valid for the C90 standard, but not for those following. implicit int (allowing to declare a function without giving its return type), and implicit declaration of functions (allowing to use a function without declaring it) are no more valid. Second, that doesn't work as you think. Result type are optional in C90, not giving one ...


8

Is there any benefit to the actual redundancy, or any risk on a more concise declaration that I haven't identified ? The C# language team have discussed removing the need for that redundancy by supporting one of the example syntaxes you cite: class Foo { private AnyClass<WithLong<Generic,Declaration>> value = new(); ... } It's ...


7

You wrote in a comment: The execution is done line-by-line. The only way to find the value returned by Func_i() is to jump out of the main That's a misconception: Execution isn't don line-by-line. Compilation is done line by line, and name resolution is done during compilation, and it only resolves names, not return values. A helpful conceptual model is ...


6

Well, his advice is slightly too simple (that's an understatement). Following it ranges all the way from a good idea over who cares and bad idea to impossible. You should follow it whenever re-using is cheaper than destroying the old and creating a new one. #include <iostream> #include <string> int main() { std::string s; // Don't ...


6

C++ Oddly enough, C++ is actually rather simpler than C (in at least some respects) when it comes to declarations vs. definitions, so let's start with it. Declaration In C++, a variable declaration would look something like: extern int a;. This tells the compiler that there's an int named a that it should assume it'll be able to access. The compiler can ...


6

There is a strong convention in java circles of not using _ for member names (as opposed to C++ circles, where there is a strong convention for using them). This is largely an arbitrary difference that probably has more to do with the desire to reinforce a sense of community than with measurable advantages. It is usually a good idea to go along with a ...


5

C and a number of other languages which require declarations were designed in an era when processor time and memory were expensive. The development of C and Unix went hand in hand for quite some time, and the latter didn't have virtual memory until 3BSD appeared in 1979. Without the extra room to work, compilers tended to be single-pass affairs because they ...


4

X in the second example is never a float. It is called a macro, it replaces the defined macro value 'X' in the source with the value. A readable article on #define is here. In the case of the supplied code, before compilation the preprocessor changes the code Z=Y+X; to Z=Y+5.2; and that is what gets compiled. That means you can also replace those '...


3

I think this is a matter of personal preference. I use underscores on private fields because I feel it makes it easier to read and identify the scope of the fields quickly. As far as I am aware, there are no rules defining which style you should use. Note: I develop in C# primarily.


3

English (and I presume other languages as well) has a lot of words which can be used in a generic sense, but are no longer correct in a context which requires more distinction. For example, you can use the word "goose" to refer to a goose of any gender or age when speaking in the more common generic sense, but if a distinction must be made, a male goose is ...


3

You must be looking at old code or code written only on Windows. K&R C and C89 required variables to be declared at the beginning of a block. C99 allows variables to be declared anywhere before they are used. The GNU C compiler has supported flexible declaration as a non-standard extension for some time. Microsoft didn't have any support for the C99 ...


2

In addition to the analysis tools, your IDE can also help you suss out these types of issues. I made the move to PyCharm because it handles these types of things much more effectively, than say, Eclipse & PyDev. It is a much more visual IDE that helps you prevent these issues.


2

In my experience, there are three ways to prevent the problems you described above: Limit the scope of your variables Name your variables something meaningful and descriptive Use a pre-compiler to notify of any errors (Doval mentioned pylint for Python) 1) Limiting the scope of your variables will limit the first error. You will have fewer variables that ...


2

Both versions may have a specific purpose. 1 Variables inside Used for iterating(yes, I know about iterators and enhanced loop, but let's use the old for) 2 Variables outside Let's say we want to find the index of an item from some array and we want that index to use for something else. You can't use the variables for the loop scope because you will ...


2

Quick answer: most of the time I don't care about the value outside the loop, so I use the second form. Occasionally I'll want the "first index" where I'll put a break (or an exit condition on the loop) so that the value represents as far as I got. Then I'll use the first form, but with a break or a loop condition that causes it to stop early. ...e.g. find ...


2

What changes you are suggesting for member variables is only a change in the compiler. There needs to be no change in the executing CLR. So such a change would be easy to bring. You would need to submit the request with Microsoft. I have also found this redundancy a slightly annoying (only slightly). However the redundancy being contained in one line ...


2

Is there a difference between defining a variable in C and assigning a value to a variable in C? You can only define a variable once but you can assign a variable multiple times. Conversely, defining a variable does not necessarily give it a value. e.g. main() { int a; printf("a has the value %d\n", a); } This will usually compile but is undefined ...


2

What you're asking about is a form of data flow analysis. The code could be translated into some form of basic blocks (or other intermediate data structure). There will be flow of control (branches) associated with the AND and OR expressions in the if-condition-test (as well as branches associated with skipping around the then-part). The basic blocks are ...


1

The core idea I don't see an issue with using a syntax similar to var variables when declaring class variables: public class Foo { var Bar = new Bar(); } All the necessary information is there, it's not ambiguous, and it follows a known syntax (variable type inference). However, a combined declaration and initialisation is a rare occurence for method ...


1

It's worse than that, Jim ... Since you tagged the question c#, you're not only wrong in assuming that there is any performance benefit (this is a trivial optimization, one any halfway-decent compiler will perform), but also in assuming that the declarations are re-executed on each loop pass. In fact, the variable will have space allocated for it at some ...


1

In the context of C#, it is hard to imagine how declaring the variable in one scope or another affects the garbage collection. In C# and Java, scope does not dictate storage reclamation (while on the other hand, it has implications in C++). Local variables, in particular in C#, are mostly free. So, declaring one in an inner scope, even if looping is ...


1

The term "argument" is often used rather loosely to refer to either actual arguments or formal arguments without giving the actual or formal adjective. Most often, the context makes it clear if actual arguments or formal arguments/parameters is meant. In this case, it should be clear that the authors meant formal arguments or parameters. As to why they didn'...


1

The short answer is C needs types because of history / representing the hardware. History: C was developed in the early 1970s and intended as a language for systems programming. Code is ideally fast and makes the best use of the capabilities of the hardware. Inferring types at compile time would have been possible, but the already slow compile times would ...


1

You must be looking at very old code, code written by people that are either not up to date on their skills, or code written by people that enjoy writing Pascal in C. Older versions of the C language spec (C89 and prior) required the declarations to be immediately following the opening brace, but since then modern compilers have eliminated that requirement. ...


Only top voted, non community-wiki answers of a minimum length are eligible