• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 21:37
CEST 03:37
KST 10:37
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL20] Ro24 Preview Pt2: Take-Off7[ASL20] Ro24 Preview Pt1: Runway132v2 & SC: Evo Complete: Weekend Double Feature4Team Liquid Map Contest #21 - Presented by Monster Energy9uThermal's 2v2 Tour: $15,000 Main Event18
Community News
Weekly Cups (Aug 18-24): herO dethrones MaxPax6Maestros of The Game—$20k event w/ live finals in Paris31Weekly Cups (Aug 11-17): MaxPax triples again!13Weekly Cups (Aug 4-10): MaxPax wins a triple6SC2's Safe House 2 - October 18 & 195
StarCraft 2
General
#2: Serral - Greatest Players of All Time #1: Maru - Greatest Players of All Time I hope balance council is prepping final balance Geoff 'iNcontroL' Robinson has passed away Aligulac - Europe takes the podium
Tourneys
Esports World Cup 2025 Sparkling Tuna Cup - Weekly Open Tournament Maestros of The Game—$20k event w/ live finals in Paris WardiTV Mondays RSL: Revival, a new crowdfunded tournament series
Strategy
Custom Maps
External Content
Mutation # 488 What Goes Around Mutation # 487 Think Fast Mutation # 486 Watch the Skies Mutation # 485 Death from Below
Brood War
General
BSL Polish World Championship 2025 20-21 September BGH Auto Balance -> http://bghmmr.eu/ ASL Season 20 Ro24 Groups Flash On His 2010 "God" Form, Mind Games, vs JD No Rain in ASL20?
Tourneys
[Megathread] Daily Proleagues [IPSL] CSLAN Review and CSLPRO Reimagined! [ASL20] Ro24 Group F [ASL20] Ro24 Group D
Strategy
Simple Questions, Simple Answers Fighting Spirit mining rates [G] Mineral Boosting Muta micro map competition
Other Games
General Games
Stormgate/Frost Giant Megathread Nintendo Switch Thread General RTS Discussion Thread Dawn of War IV Path of Exile
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread Things Aren’t Peaceful in Palestine The year 2050 European Politico-economics QA Mega-thread
Fan Clubs
INnoVation Fan Club SKT1 Classic Fan Club!
Media & Entertainment
Anime Discussion Thread Movie Discussion! [Manga] One Piece [\m/] Heavy Metal Thread
Sports
2024 - 2026 Football Thread Formula 1 Discussion TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
High temperatures on bridge(s) Gtx660 graphics card replacement Installation of Windows 10 suck at "just a moment"
TL Community
The Automated Ban List TeamLiquid Team Shirt On Sale
Blogs
RTS Design in Hypercoven
a11
Evil Gacha Games and the…
ffswowsucks
Breaking the Meta: Non-Stand…
TrAiDoS
INDEPENDIENTE LA CTM
XenOsky
[Girl blog} My fema…
artosisisthebest
Sharpening the Filtration…
frozenclaw
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1221 users

The Big Programming Thread - Page 203

Forum Index > General Forum
Post a Reply
Prev 1 201 202 203 204 205 1031 Next
Thread Rules
1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution.
2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20)
3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible.
4. Use [code] tags to format code blocks.
Tobberoth
Profile Joined August 2010
Sweden6375 Posts
November 26 2012 20:17 GMT
#4041
All loops are really more or less syntactic sugar, in machine code, they are always implemented as conditional jumps anyway. Picking the proper loop construct can do tons of readability though, and in some languages, can probably help with optimization as well.
sAsThark
Profile Joined September 2011
France27 Posts
November 26 2012 20:33 GMT
#4042
The for(Element e : myArrayList) just mean a loop on each e in myArrayList. For each loop turn, your variable e will take the next element of your list. This is an easy way to use almost every List from the Java API.

But as I said, you can also create your own class which will implements Iterable. This class must override iterator() a method which return an home made Iterator (implementing iterator) and override the following method : hadNext(), Next(), remove(). Then you should be able to use a for(Stuff s : MyBadAssList). Clearly it's a waste of time to code this for a simple application, you could be more productive using the API. BTW it's a good way to understand the mechanics of java and a good academic implementation of abstract list ...
http://fedoraproject.org/
frogmelter
Profile Blog Joined April 2009
United States971 Posts
November 26 2012 21:21 GMT
#4043
On November 27 2012 05:08 AmericanUmlaut wrote:
Show nested quote +
On November 27 2012 04:28 Ame wrote:
On November 27 2012 04:09 RoyGBiv_13 wrote:
On November 27 2012 03:36 Ame wrote:
Does anyone have a for loop off the top of their head that cannot be written as a while loop? Or the opposite? Internet said while loops work with booleans better... but for loops initialized and terminated fine with booleans when I did a test run in Java.

Is it more of a convention thing then? Such that when another programmer comes in and sees a while or for loop they can then they can make a quick assumption on the check being dependent or not?


I'm not exactly sure what you're getting at here. A for loop is the same as a while loop with some additional organizational structure for clarity's sake.

Back in old programming (BASIC/Pascal) days, they were used for seperate purposes, so convention has followed. For loops are used as loops that iterate a known number of times before the loop is encountered, whereas while loops are more of a "keep doing this until..." kind of statement.


i=0;
while(i<10) {
//do stuff
++i;
}

for(i=0;i<10;++i) {
//do stuff
}


I guess I'm looking for... reasoning for why both For and While loops even exist, instead of just one of them. If there is actually something that can be done in one of the loops that the other cannot do without the addition with many lines of code. Maybe For and While loops hit memory in different way (noob here, no idea how heap/stack/whatnot work)?

Otherwise the answer seems to be something vestigial that is just coding conventions now?

It's less a question of convention than a question of readability. If you see for(i=0; i<10; i++){...}, you instantly know what's intended without having to give it a lot of thought, whereas it takes a bit more thinking to parse a while loop that does the same thing (you have to go through the body of the loop and see everything that can happen to your i variable). While loops remain useful, though, because there are a lot of times when you don't have a number of loops you want to do, but rather you just want to loop until you encounter some stop condition, for example looping through a string and doing something with each character:

while(null !== curChar) {
curChar = myString.getNextChar();
doSomething(curChar);
}

You could technically do the same thing with a for loop, but it would be really unreadable. In fact, in terms of making a program work for and while loops could both be replaced by GOTO, which is what they devolve to at the machine code level in any case. We have these control structures not because they work better logically, but because they make code a lot more intuitive to read and write for humans. One of the most important concepts in programming as far as I'm concerned is understanding that writing code that a computer can understand (what 99% of people think we do for a living) is only the first part of the job, and is often relatively easy*. When you're good, you give as much consideration to making sure that you're writing code that a person can understand.

*Except for pointers and the Javascript SelectionRange object.

Edit to add: Another point is that for() gives you a really simple syntax for something that you do over and over and over again as a programmer. A while loop requires several lines of code to do the same thing, which multiplies your opportunites for typos, forgetting to initialize or increment your counter, and so on. One of the reasons that "elegance" is held holy by computer programmers is that if you can figure out a way to solve a problem with 3 lines of code rather than 20, then even if your 3 lines are no faster and no more logically correct than my 20, your code has only 3 things that can be wrong, and mine has 20. At the same time, if a bug in your code does pop up, the guy who gets the job of fixing it only has to understand 3 lines of code, so he'll probably be able to instantly or very quickly grasp what's being done, which might take significantly more time in a function that's much longer.


What about

for (int i = 0; i < myString.length(); ++i)
{
//do something
}

or for a c string

char c;
for (int i = 0; c != '\0'; ++i)
{
c = myString[i];
//do something
}

for looping through a string?

I would argue that the first one for a C++ string is just as readable as the while loop that you wrote, if not more.
TL+ Member
Kambing
Profile Joined May 2010
United States1176 Posts
Last Edited: 2012-11-26 23:02:37
November 26 2012 22:11 GMT
#4044
Conventionally:

For-loops are used for definite loops, those that have known or "obvious" boundary conditions, e.g., array length, length of an iterator.

While-loops are used for indefinite loops, those whose boundary conditions are not known, e.g., terminating when a user enters 'yes'.

Also, in many programming languages, this implies that using a for-loop is usually a bad idea. This is because there are usually better higher-level constructs for expressing iteration with known bounds than a for-loop, e.g., Java foreach or Python list comprehension.
omarsito
Profile Joined June 2011
22 Posts
November 26 2012 22:52 GMT
#4045
I finished a program that recently reads bytes from a file and outputs them in another file (aka copy) But when i run the program im getting a error of the kind java.lang.NullPointerException which points at a code line where i close my outputstream. I was wondering if anybody could quickly check my code because i cant figure the out problem myself, i derived the code from a tutorial but i havent been able to fix it.
Heres the code if anybody has the time to assist me !

http://justpaste.it/1kbl
RoyGBiv_13
Profile Blog Joined August 2010
United States1275 Posts
Last Edited: 2012-11-26 23:40:24
November 26 2012 23:33 GMT
#4046
--Debugging story time--

Initial Symptom:
A customer of ours recently upgraded the kernel of our proprietary OS, and were finding that occasionally the debugger was unable to flash the kernel onto the mirochip, and the whole thing crashed.

We schedule a web meeting to see this happen in action, and sure enough, the kernel loads up fine with no issues. We retry it, hoping to reproduce the issue, and again, the board works just fine. They start closing every process they can, but still, no luck.

Hmm, we check the board initialization script (to boot up the board before you flash the software onto it), and it is the same as the one we sent them and have tested extensively. Maybe it's flakey hardware? We have the customer try with a different board. Same result, it is working fine. We get off the phone, and close out the web meeting. This one is weird.

Two minutes later, a phone call from them informs us that it's flaking out again, and to quickly join the meeting. We join up, and the next try works fine "That's strange, the only thing to change has been opening up the GoTo meeting...", so while on the phone with them, we disconnect the screen viewer, and sure enough, the board fails to boot up. In disbelief, we retry the experiment a few times.

Literally, in this case, the problem is solved by being on the phone with someone from tech support. We jokingly quote them a rate to always have a tech support guy on the line, but certainly, these two completely unconnected pieces of software have no impact on each other couldn't cause the behavior of the system to change. Right?

We now have at least one piece of evidence on this heisenbug, and the ability to branch from there. Do other programs cause this? Nope. Does this same heisenbug exist on other hosts (computers launching the debugger)? Can't test.

Hmm, we take a step back. Why is the kernel failing to flash in the first place? There seems to be some registers on the board uninitialized. Checking back in the boot up script, we notice these registers are at the end of the script. There doesn't seem to be any reason for them not the be initialized. It feels like we're getting closer here. We use breakpoint debugging within the startup script to isolate the lines causing the issue.

+ Show Spoiler +
If this script has been running for 10 seconds
then shutdown the board, and stop the script


Ahh, a watchdog in the script to fail if the script is going on for too long. We check with the developers who wrote the debugger, and sure enough, the wait(n milliseconds) function uses the system timer to wait in a spin loop.
+ Show Spoiler +

The screen share was causing the system timer to slow down just enough so that the microchips initialization would finish before the host computer counted to 10. Without the GoTo meeting, the system counts just a wee bit quicker, and the startup script would exit before completing.
We increased the time to 25 seconds and everything worked fine


tl;dr - Heisenbug only reproduces when off the phone with tech support.
Any sufficiently advanced technology is indistinguishable from magic
Shield
Profile Blog Joined August 2009
Bulgaria4824 Posts
Last Edited: 2012-11-27 00:20:16
November 27 2012 00:11 GMT
#4047
I'm trying to print network output from another class, but 'out' doesn't get recognised. To be clear, here is some code:

in a class implementing Runnable (method run()):

// constructor
Class(Socket s) {
client = s;
}

public void run() {
PrintWriter out = null;

try {
out = new PrintWriter(new OutputStreamWriter (client.getOutputStream()));
... etc
}
}


However, I'm trying to send output from a method in another class. E.g.

public void sendOutput(String msg) {
Class.out.println(msg); // out doesn't get recognised, it gives 'cannot find symbol' error
}


I hope it's clear. Sorry for not releasing full code, but university is very strict with plagiarism, so I don't want them to find my code here.

I guess scope isn't big enough, but I have no idea how to expand it either. An idea is to pass a reference or something like that, but all my attemps are unsuccessful.
JeanLuc
Profile Joined September 2010
Canada377 Posts
November 27 2012 00:17 GMT
#4048
+ Show Spoiler +
On November 27 2012 08:33 RoyGBiv_13 wrote:
--Debugging story time--

Initial Symptom:
A customer of ours recently upgraded the kernel of our proprietary OS, and were finding that occasionally the debugger was unable to flash the kernel onto the mirochip, and the whole thing crashed.

We schedule a web meeting to see this happen in action, and sure enough, the kernel loads up fine with no issues. We retry it, hoping to reproduce the issue, and again, the board works just fine. They start closing every process they can, but still, no luck.

Hmm, we check the board initialization script (to boot up the board before you flash the software onto it), and it is the same as the one we sent them and have tested extensively. Maybe it's flakey hardware? We have the customer try with a different board. Same result, it is working fine. We get off the phone, and close out the web meeting. This one is weird.

Two minutes later, a phone call from them informs us that it's flaking out again, and to quickly join the meeting. We join up, and the next try works fine "That's strange, the only thing to change has been opening up the GoTo meeting...", so while on the phone with them, we disconnect the screen viewer, and sure enough, the board fails to boot up. In disbelief, we retry the experiment a few times.

Literally, in this case, the problem is solved by being on the phone with someone from tech support. We jokingly quote them a rate to always have a tech support guy on the line, but certainly, these two completely unconnected pieces of software have no impact on each other couldn't cause the behavior of the system to change. Right?

We now have at least one piece of evidence on this heisenbug, and the ability to branch from there. Do other programs cause this? Nope. Does this same heisenbug exist on other hosts (computers launching the debugger)? Can't test.

Hmm, we take a step back. Why is the kernel failing to flash in the first place? There seems to be some registers on the board uninitialized. Checking back in the boot up script, we notice these registers are at the end of the script. There doesn't seem to be any reason for them not the be initialized. It feels like we're getting closer here. We use breakpoint debugging within the startup script to isolate the lines causing the issue.

+ Show Spoiler +
If this script has been running for 10 seconds
then shutdown the board, and stop the script


Ahh, a watchdog in the script to fail if the script is going on for too long. We check with the developers who wrote the debugger, and sure enough, the wait(n milliseconds) function uses the system timer to wait in a spin loop.
+ Show Spoiler +

The screen share was causing the system timer to slow down just enough so that the microchips initialization would finish before the host computer counted to 10. Without the GoTo meeting, the system counts just a wee bit quicker, and the startup script would exit before completing.
We increased the time to 25 seconds and everything worked fine


tl;dr - Heisenbug only reproduces when off the phone with tech support.

I will henceforth refer to all elusive bugs as heisenbug
If you can't find it within yourself to stand up and tell the truth-- you don't deserve to wear that uniform
DeltaX
Profile Joined August 2011
United States287 Posts
November 27 2012 00:19 GMT
#4049
On November 27 2012 07:52 omarsito wrote:
I finished a program that recently reads bytes from a file and outputs them in another file (aka copy) But when i run the program im getting a error of the kind java.lang.NullPointerException which points at a code line where i close my outputstream. I was wondering if anybody could quickly check my code because i cant figure the out problem myself, i derived the code from a tutorial but i havent been able to fix it.
Heres the code if anybody has the time to assist me !

http://justpaste.it/1kbl


Are you sure that your program is actually finding the first file you want to read from? I ran it and got the same null pointer exception with "Storlek på Fil: 0" which would indicate that it can't find the file which my computer clearly does not contain.

Also you can get rid of the second "Meny" class if you want and put that all in your read and write class
omarsito
Profile Joined June 2011
22 Posts
Last Edited: 2012-11-27 00:47:40
November 27 2012 00:43 GMT
#4050
On November 27 2012 09:19 DeltaX wrote:

Are you sure that your program is actually finding the first file you want to read from? I ran it and got the same null pointer exception with "Storlek på Fil: 0" which would indicate that it can't find the file which my computer clearly does not contain.

Also you can get rid of the second "Meny" class if you want and put that all in your read and write class


Yeah im sure the first method is correct because im getting the correct amount of bytes when it prints out,

EDIT:
I got it working by changing the directory of the output file, it seems my computer doesnt like modifying/putting files in only C:
RoyGBiv_13
Profile Blog Joined August 2010
United States1275 Posts
November 27 2012 00:49 GMT
#4051
On November 27 2012 09:17 JeanLuc wrote:
+ Show Spoiler +
On November 27 2012 08:33 RoyGBiv_13 wrote:
--Debugging story time--

Initial Symptom:
A customer of ours recently upgraded the kernel of our proprietary OS, and were finding that occasionally the debugger was unable to flash the kernel onto the mirochip, and the whole thing crashed.

We schedule a web meeting to see this happen in action, and sure enough, the kernel loads up fine with no issues. We retry it, hoping to reproduce the issue, and again, the board works just fine. They start closing every process they can, but still, no luck.

Hmm, we check the board initialization script (to boot up the board before you flash the software onto it), and it is the same as the one we sent them and have tested extensively. Maybe it's flakey hardware? We have the customer try with a different board. Same result, it is working fine. We get off the phone, and close out the web meeting. This one is weird.

Two minutes later, a phone call from them informs us that it's flaking out again, and to quickly join the meeting. We join up, and the next try works fine "That's strange, the only thing to change has been opening up the GoTo meeting...", so while on the phone with them, we disconnect the screen viewer, and sure enough, the board fails to boot up. In disbelief, we retry the experiment a few times.

Literally, in this case, the problem is solved by being on the phone with someone from tech support. We jokingly quote them a rate to always have a tech support guy on the line, but certainly, these two completely unconnected pieces of software have no impact on each other couldn't cause the behavior of the system to change. Right?

We now have at least one piece of evidence on this heisenbug, and the ability to branch from there. Do other programs cause this? Nope. Does this same heisenbug exist on other hosts (computers launching the debugger)? Can't test.

Hmm, we take a step back. Why is the kernel failing to flash in the first place? There seems to be some registers on the board uninitialized. Checking back in the boot up script, we notice these registers are at the end of the script. There doesn't seem to be any reason for them not the be initialized. It feels like we're getting closer here. We use breakpoint debugging within the startup script to isolate the lines causing the issue.

+ Show Spoiler +
If this script has been running for 10 seconds
then shutdown the board, and stop the script


Ahh, a watchdog in the script to fail if the script is going on for too long. We check with the developers who wrote the debugger, and sure enough, the wait(n milliseconds) function uses the system timer to wait in a spin loop.
+ Show Spoiler +

The screen share was causing the system timer to slow down just enough so that the microchips initialization would finish before the host computer counted to 10. Without the GoTo meeting, the system counts just a wee bit quicker, and the startup script would exit before completing.
We increased the time to 25 seconds and everything worked fine


tl;dr - Heisenbug only reproduces when off the phone with tech support.

I will henceforth refer to all elusive bugs as heisenbug


Heh, it's supposed to refer to the fact that attempting to debug the behavior affects the behavior in the first place. http://en.wikipedia.org/wiki/Heisenbug
Any sufficiently advanced technology is indistinguishable from magic
RoyGBiv_13
Profile Blog Joined August 2010
United States1275 Posts
Last Edited: 2012-11-27 01:23:28
November 27 2012 01:22 GMT
#4052
On November 27 2012 09:11 darkness wrote:
I'm trying to print network output from another class, but 'out' doesn't get recognised. To be clear, here is some code:

in a class implementing Runnable (method run()):

// constructor
Class(Socket s) {
client = s;
}

public void run() {
PrintWriter out = null;

try {
out = new PrintWriter(new OutputStreamWriter (client.getOutputStream()));
... etc
}
}


However, I'm trying to send output from a method in another class. E.g.

public void sendOutput(String msg) {
Class.out.println(msg); // out doesn't get recognised, it gives 'cannot find symbol' error
}


I hope it's clear. Sorry for not releasing full code, but university is very strict with plagiarism, so I don't want them to find my code here.

I guess scope isn't big enough, but I have no idea how to expand it either. An idea is to pass a reference or something like that, but all my attemps are unsuccessful.


Try moving "PrintWriter out = null;" into the Class's scope, with a public static modifier, or access it via an instantiated object without the static modifier. In either case, the scope runs out with the last bracket in run(){...}, so you will have to move it into the class's scope.

Any sufficiently advanced technology is indistinguishable from magic
Shield
Profile Blog Joined August 2009
Bulgaria4824 Posts
November 27 2012 02:42 GMT
#4053
On November 27 2012 10:22 RoyGBiv_13 wrote:
Show nested quote +
On November 27 2012 09:11 darkness wrote:
I'm trying to print network output from another class, but 'out' doesn't get recognised. To be clear, here is some code:

in a class implementing Runnable (method run()):

// constructor
Class(Socket s) {
client = s;
}

public void run() {
PrintWriter out = null;

try {
out = new PrintWriter(new OutputStreamWriter (client.getOutputStream()));
... etc
}
}


However, I'm trying to send output from a method in another class. E.g.

public void sendOutput(String msg) {
Class.out.println(msg); // out doesn't get recognised, it gives 'cannot find symbol' error
}


I hope it's clear. Sorry for not releasing full code, but university is very strict with plagiarism, so I don't want them to find my code here.

I guess scope isn't big enough, but I have no idea how to expand it either. An idea is to pass a reference or something like that, but all my attemps are unsuccessful.


Try moving "PrintWriter out = null;" into the Class's scope, with a public static modifier, or access it via an instantiated object without the static modifier. In either case, the scope runs out with the last bracket in run(){...}, so you will have to move it into the class's scope.



Are you sure static is a good idea? I think the program doesn't run well. Object instance is what I've tried, but I need to find a way to do it while satisfying my constructor (variable client).
phar
Profile Joined August 2011
United States1080 Posts
Last Edited: 2012-11-27 07:42:11
November 27 2012 07:37 GMT
#4054
I don't really understand what you're trying to do.


public class Foo {

private final Socket client;
private final PrintWriter out;

Foo(Socket s) {
this.client = checkNotNull(s, "socket must not be null");
this.out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
}
}


That lets you use 'client' and 'out' anywhere in the scope of the class. If you need to use 'out' from another class, make a method to access it:

public class Foo {
...

public void writeString(String string) {
out.println(string);
}
}


Instantiate foo, call foo.writeString.

Really hard to give more specific advice without knowing the situation more. But in general, you should reserve static references from outside a class into another (e.g. Preconditions.checkNotNull) for things that do not rely on any state that can change. It's ok for helper methods that rely only on constants and arguments passed in directly to the method, but it's really not kosher to have it reference something from a constructor. What happens when someone calls that static method without having previously called the constructor? Probably lots of NPEs (if you're lucky), or random wonky shit.

There are other reasons to use or avoid static variables or static methods, but they're probably out of scope for what you need to know now.
Who after all is today speaking about the destruction of the Armenians?
AmericanUmlaut
Profile Blog Joined November 2010
Germany2577 Posts
November 27 2012 09:02 GMT
#4055
On November 27 2012 06:21 frogmelter wrote:
Show nested quote +
On November 27 2012 05:08 AmericanUmlaut wrote:
On November 27 2012 04:28 Ame wrote:
On November 27 2012 04:09 RoyGBiv_13 wrote:
On November 27 2012 03:36 Ame wrote:
Does anyone have a for loop off the top of their head that cannot be written as a while loop? Or the opposite? Internet said while loops work with booleans better... but for loops initialized and terminated fine with booleans when I did a test run in Java.

Is it more of a convention thing then? Such that when another programmer comes in and sees a while or for loop they can then they can make a quick assumption on the check being dependent or not?


I'm not exactly sure what you're getting at here. A for loop is the same as a while loop with some additional organizational structure for clarity's sake.

Back in old programming (BASIC/Pascal) days, they were used for seperate purposes, so convention has followed. For loops are used as loops that iterate a known number of times before the loop is encountered, whereas while loops are more of a "keep doing this until..." kind of statement.


i=0;
while(i<10) {
//do stuff
++i;
}

for(i=0;i<10;++i) {
//do stuff
}


I guess I'm looking for... reasoning for why both For and While loops even exist, instead of just one of them. If there is actually something that can be done in one of the loops that the other cannot do without the addition with many lines of code. Maybe For and While loops hit memory in different way (noob here, no idea how heap/stack/whatnot work)?

Otherwise the answer seems to be something vestigial that is just coding conventions now?

It's less a question of convention than a question of readability. If you see for(i=0; i<10; i++){...}, you instantly know what's intended without having to give it a lot of thought, whereas it takes a bit more thinking to parse a while loop that does the same thing (you have to go through the body of the loop and see everything that can happen to your i variable). While loops remain useful, though, because there are a lot of times when you don't have a number of loops you want to do, but rather you just want to loop until you encounter some stop condition, for example looping through a string and doing something with each character:

while(null !== curChar) {
curChar = myString.getNextChar();
doSomething(curChar);
}

You could technically do the same thing with a for loop, but it would be really unreadable. In fact, in terms of making a program work for and while loops could both be replaced by GOTO, which is what they devolve to at the machine code level in any case. We have these control structures not because they work better logically, but because they make code a lot more intuitive to read and write for humans. One of the most important concepts in programming as far as I'm concerned is understanding that writing code that a computer can understand (what 99% of people think we do for a living) is only the first part of the job, and is often relatively easy*. When you're good, you give as much consideration to making sure that you're writing code that a person can understand.

*Except for pointers and the Javascript SelectionRange object.

Edit to add: Another point is that for() gives you a really simple syntax for something that you do over and over and over again as a programmer. A while loop requires several lines of code to do the same thing, which multiplies your opportunites for typos, forgetting to initialize or increment your counter, and so on. One of the reasons that "elegance" is held holy by computer programmers is that if you can figure out a way to solve a problem with 3 lines of code rather than 20, then even if your 3 lines are no faster and no more logically correct than my 20, your code has only 3 things that can be wrong, and mine has 20. At the same time, if a bug in your code does pop up, the guy who gets the job of fixing it only has to understand 3 lines of code, so he'll probably be able to instantly or very quickly grasp what's being done, which might take significantly more time in a function that's much longer.


What about

for (int i = 0; i < myString.length(); ++i)
{
//do something
}

or for a c string

char c;
for (int i = 0; c != '\0'; ++i)
{
c = myString[i];
//do something
}

for looping through a string?

I would argue that the first one for a C++ string is just as readable as the while loop that you wrote, if not more.

You are right, strings aren't a very good example of my point. I was trying to come up with something that fit on very few lines . Parsing lines in a file or performing a behavior indefinitely until the user inputs a particular character are better examples.
The frumious Bandersnatch
KaiserJohan
Profile Joined May 2010
Sweden1808 Posts
November 27 2012 09:51 GMT
#4056
On November 27 2012 08:33 RoyGBiv_13 wrote:
--Debugging story time--

Initial Symptom:
A customer of ours recently upgraded the kernel of our proprietary OS, and were finding that occasionally the debugger was unable to flash the kernel onto the mirochip, and the whole thing crashed.

We schedule a web meeting to see this happen in action, and sure enough, the kernel loads up fine with no issues. We retry it, hoping to reproduce the issue, and again, the board works just fine. They start closing every process they can, but still, no luck.

Hmm, we check the board initialization script (to boot up the board before you flash the software onto it), and it is the same as the one we sent them and have tested extensively. Maybe it's flakey hardware? We have the customer try with a different board. Same result, it is working fine. We get off the phone, and close out the web meeting. This one is weird.

Two minutes later, a phone call from them informs us that it's flaking out again, and to quickly join the meeting. We join up, and the next try works fine "That's strange, the only thing to change has been opening up the GoTo meeting...", so while on the phone with them, we disconnect the screen viewer, and sure enough, the board fails to boot up. In disbelief, we retry the experiment a few times.

Literally, in this case, the problem is solved by being on the phone with someone from tech support. We jokingly quote them a rate to always have a tech support guy on the line, but certainly, these two completely unconnected pieces of software have no impact on each other couldn't cause the behavior of the system to change. Right?

We now have at least one piece of evidence on this heisenbug, and the ability to branch from there. Do other programs cause this? Nope. Does this same heisenbug exist on other hosts (computers launching the debugger)? Can't test.

Hmm, we take a step back. Why is the kernel failing to flash in the first place? There seems to be some registers on the board uninitialized. Checking back in the boot up script, we notice these registers are at the end of the script. There doesn't seem to be any reason for them not the be initialized. It feels like we're getting closer here. We use breakpoint debugging within the startup script to isolate the lines causing the issue.

+ Show Spoiler +
If this script has been running for 10 seconds
then shutdown the board, and stop the script


Ahh, a watchdog in the script to fail if the script is going on for too long. We check with the developers who wrote the debugger, and sure enough, the wait(n milliseconds) function uses the system timer to wait in a spin loop.
+ Show Spoiler +

The screen share was causing the system timer to slow down just enough so that the microchips initialization would finish before the host computer counted to 10. Without the GoTo meeting, the system counts just a wee bit quicker, and the startup script would exit before completing.
We increased the time to 25 seconds and everything worked fine


tl;dr - Heisenbug only reproduces when off the phone with tech support.


Awesome story, thanks for sharing!
England will fight to the last American
FreezingAssassin
Profile Blog Joined March 2010
United States455 Posts
November 27 2012 16:57 GMT
#4057
We are currently working in HTML where we use a <a href> to link two pages together as you all know. But What my question is my instructor said there was a possible way for us to link pages without copying and pasting all the a href tags to every single page just to make it work.

He said there was a way to link them from another source and it would make it that much easier. So my question is what is the other way to link them?
"I love when stupid stuff happens, it makes me look smart" - IdrA
fabiano
Profile Blog Joined August 2009
Brazil4644 Posts
November 27 2012 17:05 GMT
#4058
On November 28 2012 01:57 FreezingAssassin wrote:
We are currently working in HTML where we use a <a href> to link two pages together as you all know. But What my question is my instructor said there was a possible way for us to link pages without copying and pasting all the a href tags to every single page just to make it work.

He said there was a way to link them from another source and it would make it that much easier. So my question is what is the other way to link them?


With pure HTML I don`t really know any, but if you are using PHP and SQL (or any other server side language) you could leave your links stored in a DB and dynamically fetch for them.

You can do a lot of things with Javascript too, I suppose...
"When the geyser died, a probe came out" - SirJolt
nakam
Profile Joined April 2010
Sweden245 Posts
November 27 2012 17:07 GMT
#4059
On November 28 2012 01:57 FreezingAssassin wrote:
We are currently working in HTML where we use a <a href> to link two pages together as you all know. But What my question is my instructor said there was a possible way for us to link pages without copying and pasting all the a href tags to every single page just to make it work.

He said there was a way to link them from another source and it would make it that much easier. So my question is what is the other way to link them?

Frames?
TL Local Timezone Script - http://www.teamliquid.net/forum/viewmessage.php?topic_id=277156
FreezingAssassin
Profile Blog Joined March 2010
United States455 Posts
November 27 2012 17:14 GMT
#4060
On November 28 2012 02:05 fabiano wrote:
With pure HTML I don`t really know any, but if you are using PHP and SQL (or any other server side language) you could leave your links stored in a DB and dynamically fetch for them.

You can do a lot of things with Javascript too, I suppose...


I don't think we were supposed to do it all in HTML. But it can be done in Javascript?
"I love when stupid stuff happens, it makes me look smart" - IdrA
Prev 1 201 202 203 204 205 1031 Next
Please log in or register to reply.
Live Events Refresh
Replay Cast
00:00
SEL S2 Championship: Ro16
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
PiGStarcraft188
SpeCial 137
ProTech79
RuFF_SC2 41
Nina 39
StarCraft: Brood War
Artosis 735
Sharp 48
Icarus 3
Beast 2
Dota 2
monkeys_forever946
League of Legends
JimRising 302
Counter-Strike
Stewie2K771
taco 190
Super Smash Bros
hungrybox506
Mew2King20
Other Games
tarik_tv13368
summit1g8554
Day[9].tv841
shahzam631
C9.Mang0319
ViBE213
Maynarde123
ROOTCatZ0
Organizations
StarCraft 2
CranKy Ducklings133
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 16 non-featured ]
StarCraft 2
• OhrlRock 1
• intothetv
• AfreecaTV YouTube
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• Azhi_Dahaki2
• iopq 1
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• Doublelift4336
• Stunt267
Other Games
• Day9tv841
Upcoming Events
The PondCast
8h 24m
WardiTV Summer Champion…
9h 24m
herO vs MaxPax
Clem vs Classic
Replay Cast
22h 24m
LiuLi Cup
1d 9h
MaxPax vs TriGGeR
ByuN vs herO
Cure vs Rogue
Classic vs HeRoMaRinE
Cosmonarchy
1d 14h
OyAji vs Sziky
Sziky vs WolFix
WolFix vs OyAji
Big Brain Bouts
1d 14h
Iba vs GgMaChine
TriGGeR vs Bunny
Reynor vs Classic
Serral vs Clem
BSL Team Wars
1d 17h
Team Hawk vs Team Dewalt
BSL Team Wars
1d 17h
Team Hawk vs Team Bonyth
SC Evo League
2 days
TaeJa vs Cure
Rogue vs threepoint
ByuN vs Creator
MaNa vs Classic
Maestros of the Game
2 days
ShoWTimE vs Cham
GuMiho vs Ryung
Zoun vs Spirit
Rogue vs MaNa
[ Show More ]
[BSL 2025] Weekly
2 days
SC Evo League
3 days
Maestros of the Game
3 days
SHIN vs Creator
Astrea vs Lambo
Bunny vs SKillous
HeRoMaRinE vs TriGGeR
BSL Team Wars
3 days
Team Bonyth vs Team Sziky
BSL Team Wars
3 days
Team Dewalt vs Team Sziky
Monday Night Weeklies
4 days
Replay Cast
4 days
Sparkling Tuna Cup
5 days
Replay Cast
6 days
Liquipedia Results

Completed

CSL Season 18: Qualifier 1
uThermal 2v2 Main Event
HCC Europe

Ongoing

Copa Latinoamericana 4
BSL 20 Team Wars
KCM Race Survival 2025 Season 3
BSL 21 Qualifiers
ASL Season 20
Acropolis #4 - TS1
CSL Season 18: Qualifier 2
SEL Season 2 Championship
WardiTV Summer 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1
BLAST.tv Austin Major 2025

Upcoming

CSL 2025 AUTUMN (S18)
LASL Season 20
BSL Season 21
BSL 21 Team A
Chzzk MurlocKing SC1 vs SC2 Cup #2
RSL Revival: Season 2
Maestros of the Game
EC S1
Sisters' Call Cup
Skyesports Masters 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
MESA Nomadic Masters Fall
Thunderpick World Champ.
CS Asia Championships 2025
Roobet Cup 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2025 TLnet. All Rights Reserved.