Why two loops in Programming Languages? [closed] - loops

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Since I started learning programming, In every language i learn, there's always a while loop and for loop.
As while can do all those thing which for loop can. Both perfoms the same functionality to iterate. then what was the purpose of adding a for loop?
Is there any performance difference in using them? Why there are two loops in every language?

I assume you're talking about the typical for loop used in for example C/C++.
Though a for loop can always be rewritten into a while loop, it has a big readability advantage: All the loop related properties
initalization
testing
post loop operation (typically an increase or traversing)
can be captured in one line. If you have a longer body with a while loop, the whole thing might not fit your screen size, or even if it fits you have to visually parse the code to see what's going on.
In essence, if applicable, the for loop captures better the intent of your code.

The only difference is in the code readability, at compilation time the for loop is translated in a while loop with a previous initialization and a following incrementation.

for loop is used when we know the terminating condition.
while loop is generally used if we don't know the terminating condition or better we can say when we don't care what the terminating condition will be...and performance wise both will same

Since it's the condition that makes a loop "a loop", and in both cases the condition is provided by the user (and it's not part of the loop construct translation to machine code) I suspect they exist in different flavors more as a documentation tool than anything else. However the for loop enables you to declare local variables that exist only for the duration of the loop:
for (Iterator it = c.begin(); it != c.end(); ++it) {
} // it destroyed here
Ofc you can do without all loops; a goto is suficient

Related

How can pointers improve program efficiency? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
In C I have noted that pointers result in faster program execution. How is it possible, as it must fetch the pointer variable before going to the actual variable?
Pointers don't result in faster program execution. Smart algorithms result in faster program execution. Sometimes algorithms can be made smarter by using pointers in the right way. Pointers are never a magic wand to throw at problems to make the solutions faster.
Pointers are just a design paradigm though, using functional programming you do not use any pointers at all.
This is not true. The reason for faster program execution is not the availablility of pointers. It's a question of what you do with the pointers. The (possibly) faster program execution yields from the fact that no hidden functionality is introduced with C.
Take a string for example. Common implementations in other languages introduce a length field along with the string in order to keep track of the length of the string. This "bookkeeping" (although hidden from the programmer) causes extra cycles to be executed.
Another example is the fact that C does not check if the pointer you are dereferencing is valid or not. This evaluation would also cost extra cycles.
The C standard does not specify any required speed, so it doesn't make sense to attribute speed to features of C. Consider that some C implementations produce more optimal machine code than others, and it might make more sense to attribute speed to aspects of specific implementations of C1. Don't confuse implementation and specification.
1: To make a meaningful comparison of the speed of specific implementations of C, you'd probably want to mention your OS (major and minor version), your compiler (major and minor version), your CPU (model), mainboard, memory (model and configuration) and the command line arguments you used.
While I am aware every answer to the question come from people far more knowledgeable than me in C (and I am out of my league actually), IMVHO and/or limited knowledge, pointers do improve efficiency.
To answer the OP's question (and ignoring the rest about program execution and fetching):
How can pointers improve program efficiency?
By avoiding duplication of data. Although this efficiency may only be notable when dealing with user-defined variables, "structures".
Here is a nice read I found on C pointers: Why C has Pointers

calling functions in C [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
My question is particulary to function calls in C. So, either we can call functions normally or through function pointers. When your interface remainas the same but with different implementations, function pointers are used, but even if you have a single implementation having function pointers can improve the readabilty of the code.
So, what are the benefits of having static calls rather than dynamic function pointers. The call will obviously be implemented in 2 instructions as the address of the function needs to be fetched, but return will take equal cycles. I just want to understand, how can if at all processor and compiler optimize static calls over dynamic functions pointers?
Thanks,
Calling a function through a pointer will in most cases result in the compiler not being able to inline the call (if the compiler has determined that it would be beneficial to do so.) In some cases, the compiler is even able to determine the result of a function call at compile time, and thus optimize-away the whole code of the function. Function pointers also prevent this from happening.
That doesn't mean that the impact will be noticeable in any way that actually matters though. The only way to determine that, is to go and benchmark/profile your code.
However, I don't see how function pointers would be able to provide better code readability. You might want to give an example of that.
In general, direct call allows way more optimization to the compiler.
If there is really only one implementation and compiler can see it [*], it can optimize and do exactly as with direct call. But it of course depends on how smart the compiler is and what optimization options you use.
[*] i.e. if the pointer value is known in compile time; i.e. if it is 'static' variable, its address never passed outside the compilation unit, etc.

Segfault when NOT using printf [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am using POSIX threads, and at the end of my program, I am waiting to join each of the threads. After some time of running perfectly well, my code started returning a weird bug when I was waiting for the threads.
pthreads threads[C+P];
for(i = 0; i < (C+P); i++)
{
printf("%d\n", i);
pthread_join(threads[i]);
}
If I remove the printf statement, or replace it with any other printf statement, a delay, or any other operation on i, I still get a segfault.
How would I start debugging this?
Inserting printf() call affects memory layout (and thus it can, by pure accident, mask some memory corruption), as well as execution timing (you use threads, so timing is also relevant).
But instead of any sort of guesswork, you should do some regular debugging:
run you executable under gdb, this way you should be able to see what exact operation is causing a crash, where is it called from, etc.
run it under valgrind - this tool detects a lot of common errors, like accessing free'd memory block, using uninitialized variables, exceeding array/buffer boundaries, etc. It's not uncommon to immediately get exact position of the error with valgrind, I highly recommend it!

Code can stop working with compiler optimization [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm using the PellesC C compiler. Sometimes my code randomly stops working. A particular statement can trigger it. For example, I multiplied a variable by sin(c) (c is a double) and my code seemed to just finish execution with no result. Sometimes it freezes, sometimes it appears to just return, but I can always fix it by removing the offending statement or disabling compiler optimizations, specifically "maximize speed" or "maximize speed more". The freezing will also go away nearly 100% of the time if I add a printf statement somewhere near the point at which it crashes. I've never found anything to suggest that I am accessing memory improperly, I'm fairly sure its a compiler issue. I was wondering if anybody could shed some light on this. Is it possible that I am, in fact, doing something wrong? Or is this a known issue with the Pelles C compiler?
Edit:
Changing
canvas->pixels[(y*canvas->pitch)+(x*canvas->Bpp)+2]=(unsigned char)(255.0*dtempA*(1-sin(c)));
canvas->pixels[(y*canvas->pitch)+(x*canvas->Bpp)+1]=(unsigned char)(255.0*dtempA*(1+cos(c)));
canvas->pixels[(y*canvas->pitch)+(x*canvas->Bpp)]=(unsigned char)(255.0*dtempA*(1+sin(c)));
to (difference at the end of the last line)
canvas->pixels[(y*canvas->pitch)+(x*canvas->Bpp)+2]=(unsigned char)(255.0*dtempA*(1-sin(c)));
canvas->pixels[(y*canvas->pitch)+(x*canvas->Bpp)+1]=(unsigned char)(255.0*dtempA*(1+cos(c)));
canvas->pixels[(y*canvas->pitch)+(x*canvas->Bpp)]=(unsigned char)(255.0*dtempA*(1+1));
makes it work.
It could be either but a good bet is that it's you :) Variables that are not explicitly initialized will often get different values in a optimized vs an un-optimized build because the stack layout can change subtly depending on how aggressively the compiler removes temporaries, as well as other factors.
You're probably accidentally using undefined behavior somewhere, and changing random instructions in the program is breaking the very fragile alignment of the code on the stack that happens to make the program work.

Execute code inside an if(0) block [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
A challenge for all the C experts out there:
On a linux machine, you have an already compiled C program, and you are given its source code:
...
char buffer[20];
int code;
gets(buffer);
if(code==1234) ...
...
...
if(0) func();
You don't posses root privileges and the program is read-only. Find a way to execute func. I am certain this is possible, so please don't post any "It isn't possible" answers.
Good luck!
The answer lies in the unchecked buffer overflow that is waiting to happen with gets(buffer); and an understanding of what the stack looks like.
You could try setting the return address to the func() call by overflowing buffer.
http://en.wikipedia.org/wiki/Stack_buffer_overflow#Exploiting_stack_buffer_overflows
It may or may not be possible. If there are no other references to func(), the compiler may well have decided not to generate code for it in the first place -- dead code can be optimized away entirely.
This question is pretty underspecified, anyway. What do you mean by "the program is read-only"? The source code, or the executable? Are we attacking it from inside the process at runtime, inside the process by changing the source code, outside the process by trying to invoke it in funny ways, ...?
If the compiler generated code for the function (i.e. it didn't get chopped by the dead code optimizer) and you have a debugger and debug symbols, just attach a debugger and tell it to find and invoke func().
If you want to exploit the code at runtime, you can cause a buffer overflow in gets(), and take control of the process from inside, but you still have to find func() so you can jump to it -- having the source code won't help you here, and nothing will help you here if the compiler didn't generate code for it.
Since we have the source code, I would make the following edit and recompile:
-if(0) func();
+func();
Serious answer, there are thousands of ways of doing it (hacked environments, buffer overflows, etc), but the common pitfall is that a good compiler should optimize if (0) {} away. If that is the case there would be no way of executing func(). If not, then I would just start up my trusty debugger and jumping to the right spot.
Obviously, execute the famous set 0=1 command before running your executable.
But seriously, this is way off-topic...

Resources