Converting While Loop to For Loop - c

New programmer here,
How would I convert this while loop to a for loop?
while(continue()){
printf("test")
}

You wouldn't, really, the while loop is the best construct for that particular use case. A for loop has a setup step, continuation condition, and post-iteration step, and you only need the second of those (which is what while uses anyway).
But, if you really wanted to do this, it would be something like:
for(;continue();)
It's not something I, or probably any sane person, would do :-)

Most of people would prefer while in this case, but for would look like this:
for(;continue();)
{
printf("test");
}

Related

Indexing ones into a matrix of zeros without loops

I'm fairly new to MATLAB and I need some help with this problem.
the problem is to write a function that creates an (n-n) square matrix of zeros with ones on the reverse diagonal
I tried this code:
function s=reverse_diag(n)
s=zeros(n);
i=1;j=n;
while i<=n && j>=1
s(i,j)=1;
i=i+1;
j=j-1;
end
but I want another way for solving it without using loops or diag and eye commands.
Thanks in advance
The easiest and most obvious way to achieve this without loops would be to use
s=fliplr(eye(n))
since you stated that you don't want to use eye (for whatever reason), you could also work with sub2ind-command. It would look like this:
s=zeros(n);
s(sub2ind(size(s),1:size(s,1),size(s,2):-1:1))=1

Using multiple assignment to do what array.insert does?

I'm going through the code on a sample solution to my first Ruby Quiz (The Solitaire Cipher), and ran across this little nugget:
def move_down( index )
if index == #deck.length - 1
#deck[1..1] = #deck[index], #deck[1]
#deck.pop
else
...
end
end
The person who wrote this solution apparently used the multiple assignment in the second line to insert #deck[index] into the position before #deck[1]. Why not just use this?
#deck.insert(1, #deck[index])
Is there a difference?
OK, now I see what you mean. Sure, they will give the same result. I guess it just would be matter of choosing which style is more clear for you, or how you think your code would be easier to understand and in consequence more maintainable.
If your question is about which method is more "performant" I don't know that answer and I don't think it evens matters, as ruby is not meant to be performant but to be expressive.

purpose of if (true)

I've seen some code written like this:
if (true) {
... // do something
}
Why would you want to do something like this? Is there any thing special about this structure?
THanks
Pretty much any modern compiler would just optimize this away. My guess is that someone put it there during development to let them easily remove a block of code (by changing true to false), and either forgot or didn't bother to remove it when they were done.
This is one of many ways to segment out code during testing/development. Many might debate whether or not it is good coding practice, but it can be a quick and handy way to compartmentalize code. It is also a quick way to execute code that follows a complex conditional statement that you want to test.
Might be able to use it like this:
/* if (my_comlex_or_rare_conditional_case) then */
if (true) then
{
lots of code here....
} /*End if */
There have been times where I've added true || or false && inside a condition to force it to execute the branch and test the code - but only during development. The code you've posted doesn't need the if condition.

Does bracket placement affect readability? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Formatting of if Statements
Is there a best coding style for identations (same line, next line)?
Best way to code stackoverflow style 'questions' / 'tags' rollover buttons
public void Method {
}
or
public void Method
{
}
Besides personal preference is there any benefit of one style over another? I used to swear by the second method though now use the first style for work and personal projects.
By readability I mean imagine code in those methods - if/else etc...
Google C++ Style Guide suggests
Return type on the same line as function name, parameters on the same line if they fit.
Functions look like this:
ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {
DoSomething();
...
}
WebKit Coding Style Guidelines suggests
Function definitions: place each brace on its own line.
Right:
int main()
{
...
}
Wrong:
int main() {
...
}
They suggest braces-on-same-line for everything else, though.
GNU Coding Standards suggests
It is important to put the open-brace that starts the body of a C function in column one, so that they will start a defun. Several tools look for open-braces in column one to find the beginnings of C functions. These tools will not work on code not formatted that way.
Avoid putting open-brace, open-parenthesis or open-bracket in column one when they are inside a function, so that they won't start a defun. The open-brace that starts a struct body can go in column one if you find it useful to treat that definition as a defun.
It is also important for function definitions to start the name of the function in column one. This helps people to search for function definitions, and may also help certain tools recognize them. Thus, using Standard C syntax, the format is this:
static char *
concat (char *s1, char *s2)
{
...
}
or, if you want to use traditional C syntax, format the definition like this:
static char *
concat (s1, s2) /* Name starts in column one here */
char *s1, *s2;
{ /* Open brace in column one here */
...
}
As you can see, everybody has their own opinions. Personally, I prefer the Perl-ish braces-on-same-line-except-for-else, but as long as everybody working on the code can cooperate, it really doesn't matter.
I think it is completely subjective, however, I think it is important to establish code standards for your team and have everyone use the same style. That being said I like the second one (and have made my team use it) because it seems easier to read when it is not your code.
In the old days we used to use the first style (K & R style) because screens were smaller and code was often printed onto this stuff called paper.
These days we have big screen and the second method (ANSI style) makes it easier to see if your brackets match up.
See HERE and HERE for more information.
First one is smaller in terms of number of lines (maybe that is why development -Java- books tend to use that syntax)
Second one is, IMHO easier to read as you always have two aligned brackets.
Anyway both of them are widely used, it's a matter of your personal preferences.
I use the if statement as something to reason on in this highly emotive subject.
if (cond) {
//code
}
by just asking what does the else statement look like? The logical extension of the above is:-
if (cond) {
//code
} else {
//more code
}
Is that readable? I don't think so and its just plain ugly too.
More lines is != less readable. Hence I'd go with your latter option.
Personally I find the second one more readable (aligned curlys).
Its always easiest for a team to go with the defaults, and since Visual Studio and I agree on this, thats my argument. ;-)
Your lines of code count will be considerably less with the first option. :)

C functions overusing parameters?

I have legacy C code base at work and I find a lot of function implementations in the style below.
char *DoStuff(char *inPtr, char *outPtr, char *error, long *amount)
{
*error = 0;
*amount = 0;
// Read bytes from inPtr and decode them as a long storing in amount
// before returning as a formatted string in outPtr.
return (outPtr);
}
Using DoStuff:
myOutPtr = DoStuff(myInPtr, myOutPtr, myError, &myAmount);
I find that pretty obtuse and when I need to implement a similar function I end up doing:
long NewDoStuff(char *inPtr, char *error)
{
long amount = 0;
*error = 0;
// Read bytes from inPtr and decode them as a long storing in amount.
return amount;
}
Using NewDoStuff:
myAmount = NewDoStuff(myInPtr, myError);
myOutPtr += sprintf (myOutPtr, "%d", myAmount);
I can't help but wondering if there is something I'm missing with the top example, is there a good reason to use that type of approach?
One advantage is that if you have many, many calls to these functions in your code, it will quickly become tedious to have to repeat the sprintf calls over and over again.
Also, returning the out pointer makes it possible for you to do things like:
DoOtherStuff(DoStuff(myInPtr, myOutPtr, myError, &myAmount), &myOther);
With your new approach, the equivalent code is quite a lot more verbose:
myAmount = DoNewStuff(myInPtr, myError);
myOutPtr += sprintf("%d", myAmount);
myOther = DoOtherStuff(myInPtr, myError);
myOutPtr += sprintf("%d", myOther);
It is the C standard library style. The return value is there to aid chaining of function calls.
Also, DoStuff is cleaner IMO. And you really should be using snprintf. And a change in the internals of buffer management do not affect your code. However, this is no longer true with NewDoStuff.
The code you presented is a little unclear (for example, why are you adding myOutPtr with the results of the sprintf.
However, in general what it seems that you're essentially describing is the breakdown of one function that does two things into a function that does one thing and a code that does something else (the concatenation).
Separating responsibilities into two functions is a good idea. However, you would want to have a separate function for this concatenation and formatting, it's really not clear.
In addition, every time you break a function call into multiple calls, you are creating code replication. Code replication is never a good idea, so you would need a function to do that, and you will end up (this being C) with something that looks like your original DoStuff.
So I am not sure that there is much you can do about this. One of the limitations of non-OOP languages is that you have to send huge amounts of parameters (unless you used structs). You might not be able to avoid the giant interface.
If you wind up having to do the sprintf call after every call to NewDoStuff, then you are repeating yourself (and therefore violating the DRY principle). When you realize that you need to format it differently you will need to change it in every location instead of just the one.
As a rule of thumb, if the interface to one of my functions exceeds 110 columns, I look strongly at using a structure (and if I'm taking the best approach). What I don't (ever) want to do is take a function that does 5 things and break it into 5 functions, unless some functionality within the function is not only useful, but needed on its own.
I would favor the first function, but I'm also quite accustomed to the standard C style.

Resources