Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C for loop implemented differently than other languages?

Tags:

c++

c

knuth

I read the following in a review of Knuth's "The Art of Computer Programming":

"The very 'practicality' means that the would-be CS major has to learn Kernighan's mistakes in designing C, notably the infamous fact that a for loop evaluates the for condition repeatedly, which duplicates while and fails to match the behavior of most other languages which implement a for loop."

(http://www.amazon.com/review/R9OVJAJQCP78N/ref=cm_cr_pr_viewpnt#R9OVJAJQCP78N)

What is this guy talking about? How could you implement a for loop that wasn't just syntactic sugar for a while loop?

like image 991
Tristan Havelick Avatar asked Oct 23 '08 13:10

Tristan Havelick


People also ask

Are loops same in all programming languages?

Almost all the programming languages provide a concept called loop, which helps in executing one or more statements up to a desired number of times. All high-level programming languages provide various forms of loops, which can be used to execute one or more statements repeatedly.

How does C differ from other languages?

C is a Procedural Oriented language, whereas C++ is an Object-Oriented Programming language. C supports only Pointers whereas C++ supports both pointers and references. C does not allow you to use function overloading whereas C++ allows you to use function overloading.

How for in loop in Python differ from for loop of C?

For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other languages.

Are for loops same in C and Java?

Java Simple for LoopA simple for loop is the same as C/C++. We can initialize the variable, check condition and increment/decrement value.


1 Answers

Consider this:

for i:=0 to 100 do { ... }

In this case, we could replace the final value, 100, by a function call:

for i:=0 to final_value() do { ... }

... and the final_value-function would be called only once.

In C, however:

for (int i=0; i<final_value(); ++i) // ...

... the final_value-function would be called for each iteration through the loop, thus making it a good practice to be more verbose:

int end = final_value();
for (int i=0; i<end; ++i) // ...
like image 198
Magnus Hoff Avatar answered Sep 23 '22 21:09

Magnus Hoff