• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 13:02
CET 19:02
KST 03:02
  • 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
RSL Season 3 - Playoffs Preview0RSL Season 3 - RO16 Groups C & D Preview0RSL Season 3 - RO16 Groups A & B Preview2TL.net Map Contest #21: Winners12Intel X Team Liquid Seoul event: Showmatches and Meet the Pros10
Community News
Weekly Cups (Nov 24-30): MaxPax, Clem, herO win2BGE Stara Zagora 2026 announced15[BSL21] Ro.16 Group Stage (C->B->A->D)4Weekly Cups (Nov 17-23): Solar, MaxPax, Clem win3RSL Season 3: RO16 results & RO8 bracket13
StarCraft 2
General
Chinese SC2 server to reopen; live all-star event in Hangzhou Maestros of the Game: Live Finals Preview (RO4) BGE Stara Zagora 2026 announced Weekly Cups (Nov 24-30): MaxPax, Clem, herO win SC2 Proleague Discontinued; SKT, KT, SGK, CJ disband
Tourneys
Sea Duckling Open (Global, Bronze-Diamond) $5,000+ WardiTV 2025 Championship Constellation Cup - Main Event - Stellar Fest RSL Revival: Season 3 Tenacious Turtle Tussle
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 502 Negative Reinforcement Mutation # 501 Price of Progress Mutation # 500 Fright night Mutation # 499 Chilling Adaptation
Brood War
General
Which season is the best in ASL? Data analysis on 70 million replays BGH Auto Balance -> http://bghmmr.eu/ [ASL20] Ask the mapmakers — Drop your questions BW General Discussion
Tourneys
[Megathread] Daily Proleagues [BSL21] RO16 Group B - Sunday 21:00 CET [BSL21] RO16 Group C - Saturday 21:00 CET Small VOD Thread 2.0
Strategy
Game Theory for Starcraft How to stay on top of macro? Current Meta PvZ map balance
Other Games
General Games
ZeroSpace Megathread Nintendo Switch Thread Stormgate/Frost Giant Megathread The Perfect Game 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
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
Mafia Game Mode Feedback/Ideas TL Mafia Community Thread
Community
General
Russo-Ukrainian War Thread Things Aren’t Peaceful in Palestine US Politics Mega-thread The Big Programming Thread Artificial Intelligence Thread
Fan Clubs
White-Ra Fan Club
Media & Entertainment
[Manga] One Piece Movie Discussion! Anime Discussion Thread
Sports
2024 - 2026 Football Thread Formula 1 Discussion NBA General Discussion
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
Where to ask questions and add stream? The Automated Ban List
Blogs
James Bond movies ranking - pa…
Topin
Esports Earnings: Bigger Pri…
TrAiDoS
Thanks for the RSL
Hildegard
Saturation point
Uldridge
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1610 users

The Big Programming Thread - Page 454

Forum Index > General Forum
Post a Reply
Prev 1 452 453 454 455 456 1032 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.
nunez
Profile Blog Joined February 2011
Norway4003 Posts
March 10 2014 19:50 GMT
#9061
so pointers, not just references?
conspired against by a confederacy of dunces.
RoyGBiv_13
Profile Blog Joined August 2010
United States1275 Posts
Last Edited: 2014-03-10 22:36:50
March 10 2014 22:15 GMT
#9062
Pointers can be one of the more difficult concepts to understand when you first learn programming, or switch from a higher level language to a lower level one, if you aren't familiar with how memory is managed and variables stored. Admittedly, it took me a few weeks to understand a single exercise in Chapter 6: Pointers in my Learn C++ in 21 days book when I first endeavoured into the language.

Look at the below four definitions for variables:


uint32_t i;
uint32_t * j;
class_type class_var;
class_type * class_ptr;


The first line, declaring i, reserves a 32-bit space of memory. If it is declared within a function scope, that memory is ontop of the stack which is a memory structure reserved for each thread of execution. As that function enters scope, memory will be reserved for that function's variables, including i, and as that function exits scope, its variables and their associated memory will be removed from the stack.

If you have code such as the following:


int do_fib(int num)
{
int x;
//do stuff
return x;
}


Both "num" and "x" will get space on the stack. If this function were to be called several times, each copy of those variables would have a place on the stack. In this case, "num" being passed to the function directly onto the stack is called "passing by value". This means that do_fib could change the value of "num" without affecting the value anywhere else in memory, since it has it's own copy.

What about if "i" is declared in global scope, where there is no stack? In that case, the linker will reserve a bit of memory somewhere in the addresses of the ".data" section, or ".rodata" section if its declared as a constant. This is one of the ways the same variable can be accessed from different threads of execution, that don't share stack memory with each other.

The second line, uint32_t * j;, will do almost the same thing as the first line. The memory reserved, though, will not contain an integer data type, but rather, an address of somewhere in memory that contains a 32-bit integer. The actual size of the memory reserved for this pointer depends on your architecture, but for most cases, it will be 32-bits as well (unless you're compiling for a 64-bit target, or 16-bit target, etc...).

A pointer holds a location in memory of a variable called an "address". An address of a variable will look just like a big integer, but it tells the computer where in the memory to look for the variable. Lets look at some code that gets an address of a variable.

uint32_t i = 11;
uint32_t * j = &i;
printf("&p",(void *)j);

Assuming this code was within a function call, it would print out a location somewhere on the stack. If i and j were declared in a global scope, you would see the pointer pointing to somewhere in the .data section. An address could look something like 0x40003572, though that won't mean much until you look at the memory layout of your system to find out where the address is.

Classes work the same way that a primitive data type such as integers work. Declaring it within a function reserves memory on the stack, declaring a pointer will only reserve the pointer size, instead of the entire Class's size. Assuming class_type is huge, 1 megabyte or so, putting it on the stack could quickly overflow the stack or crash the program. Especially if you call the same function many times. Instead, its useful to pass classes to functions "by reference":

void set_data_times_three(class_type *my_class, uint32_t foo)
{
foo = foo*3;
my_class->data=foo;
}

This will create a copy of "foo" on the stack, as well as a pointer to the memory where my_class is stored. Only 64 bits instead of 1 megabyte was needed! When the function multiplies foo times three and stores it in the same location, it will not affect the "foo" that the calling function passed. The value of the memory where my_class->data is stored will be modified, however, so the calling function would be able to see that.

This way, functions in C can effectively modify as many variables as it wants, and functions higher up the stack can see the changes. This has created the commonly used standard in C of using function return values as error codes, rather to give information back to the caller, and instead passing variables intending to be modified by reference.

Now lets take a look at the syntax to use pointers:
+ Show Spoiler +

int * x; //putting an asterisk in a variable declaration will make it a pointer to the type just described before the asterisk. x is type: pointer to an int;
x = &a //putting an ampersand before a variable will return a reference to that variable. The value at x is the address of a
int foo = *x //putting an asterisk before a variable will "dereference" that address held by the variable, returning the value being pointed at. Update the value of foo with the value being pointed at by x (in this case, a).
myclass_ptr->data=foo; //The -> pointing arrow means the same thing as (* myclass).data. It means to use the value being pointed to by myclass_ptr, not the value of myclass_ptr itself for the dot operation.


Finally, looking back at the problem of where to put my_class if its a huge class, there is another space in memory, outside of .data and the stack, called the "heap". This is where you put variables in memory that you want to stick around, but not forever like a global variable, and that may be large. Calling "malloc", or "new" will assign a space of memory in the heap, and return that address or value.

Feel free to ask any questions, however specific. I work at a C/C++ compiler company. Now I just need someone to ask a question regarding threads so I can pick up on how operating systems handle memory between multiple running programs.

So you come form a high level language and were curious what this means to you: + Show Spoiler +

It depends language to language, but commonly, as in Java, primitive types are passed by value, and Object types are passed by reference. The compiler/interpreter will do all the pointer operations for you when it does a pass by reference, so it looks the same as in pass by value. Arrays are treated as objects, and will be passed by reference.

Java also does not manage several separate data areas to store the variables, and has a more advanced garbage collection system to handle cleaning up variables than pushing and popping them off the stack.

Exceptions are treated as a separate thread of execution, even in C++, and will often have their own stack.
Any sufficiently advanced technology is indistinguishable from magic
nunez
Profile Blog Joined February 2011
Norway4003 Posts
Last Edited: 2014-03-11 01:36:42
March 11 2014 00:37 GMT
#9063
a knowledge bomb!
i think c++ newbies should take care not to conflate pointer with reference;

this was confusing for a while to me, consider:

f(int* v);
g(int*& v);

and

int* a;


f(a) will pass a copy of the pointer a. so v's pointee in a will have the same address as a's pointee, but v itself will have a different address than a.
g(a) will pass the reference to pointer, here both v and v's pointee have the same address as a and a's pointee respectively.

thus changes to v itself in f(a) will not be visible in a, since v in f(a) is merely a copy. however changes to v itself g(a) is equivalent to changing a itself. in both cases changes to a's pointee will be visible ofc. i think 'alias' makes sense for reference, but not really for pointer (to me).

that's sounds like an awesome job btw roygbv.
conspired against by a confederacy of dunces.
phar
Profile Joined August 2011
United States1080 Posts
March 11 2014 01:46 GMT
#9064
I present to you March's ;login: logout, featuring James Micken's last column:

https://www.usenix.org/system/files/1403_02-08_mickens.pdf

If you are a frontend programmer, you may need to read it in smaller chunks to avoid dying from a twisted combination of laughter and pain.
Who after all is today speaking about the destruction of the Armenians?
Manit0u
Profile Blog Joined August 2004
Poland17494 Posts
Last Edited: 2014-03-11 02:08:10
March 11 2014 02:06 GMT
#9065
On March 11 2014 07:15 RoyGBiv_13 wrote:
Feel free to ask any questions, however specific. I work at a C/C++ compiler company. Now I just need someone to ask a question regarding threads so I can pick up on how operating systems handle memory between multiple running programs.


I've got a question for you. Albeit it might be a stupid one since I'm just an amateur dabbler in programming for the most part and never learned the "behind the scenes" stuff as I never really needed that much knowledge. Well, now I'm interested in going deeper with my knowledge and want to apply better and more efficient practices when I write the code.

My question (please don't laugh if it's stupid):

int some_func(int num)
{
int x = num;

do stuff with x;

return x;
}


Is there any real difference if I pass the variable to the function, then assign the variable's value to another variable or if I work with the passed variable directly bar the readability?


int some_func(int num)
{
return (do stuff with num);
}


Note: I used simple int in the example, but what if that's actually an entire mapping or somesuch bigger data structure?
Time is precious. Waste it wisely.
necrosexy
Profile Joined March 2011
451 Posts
March 11 2014 02:32 GMT
#9066
how do i specify where the java compiler places output?
Cyx.
Profile Joined November 2010
Canada806 Posts
Last Edited: 2014-03-11 02:41:43
March 11 2014 02:38 GMT
#9067
On March 11 2014 11:06 Manit0u wrote:
Show nested quote +
On March 11 2014 07:15 RoyGBiv_13 wrote:
Feel free to ask any questions, however specific. I work at a C/C++ compiler company. Now I just need someone to ask a question regarding threads so I can pick up on how operating systems handle memory between multiple running programs.


I've got a question for you. Albeit it might be a stupid one since I'm just an amateur dabbler in programming for the most part and never learned the "behind the scenes" stuff as I never really needed that much knowledge. Well, now I'm interested in going deeper with my knowledge and want to apply better and more efficient practices when I write the code.

My question (please don't laugh if it's stupid):

int some_func(int num)
{
int x = num;

do stuff with x;

return x;
}


Is there any real difference if I pass the variable to the function, then assign the variable's value to another variable or if I work with the passed variable directly bar the readability?


int some_func(int num)
{
return (do stuff with num);
}


Note: I used simple int in the example, but what if that's actually an entire mapping or somesuch bigger data structure?


The only difference is that you make an extra copy in the first one ^^ The compiler makes a copy anyways when you pass by value like that, so unless the parameters are references, all you do is waste time (that the compiler probably optimizes away anyways).

EDIT:
On March 11 2014 11:32 necrosexy wrote:
how do i specify where the java compiler places output?


javac -d [pathname] [java file name]
SilverSkyLark
Profile Blog Joined April 2008
Philippines8437 Posts
March 11 2014 06:37 GMT
#9068
Uh hi guys, sorry but I've been working on this for quite some time and I'm stuck. This is iOS 7 btw.

I have a tableView with custom cells containing the item name, price, and discount (if available). There is also a textField for the quantity and the user requested discount. The user selects the rows of the items he wants and fills up those two textFields. The user then clicks a button and what I want to do is to get the item name, price, discount, quantity, and user requested discount and store those in arrays. Before I go on, here are relevant code:

The Mutable Arrays I used:
+ Show Spoiler +


//these are the arrays where I get the price, discount, and item names from, they are populated via database query
priceList;
discountList;
searchResults;
checkList; //I need this to mark which index rows were selected since I put a checkmark on those

//these are the arrays where I plan to put the user input
itemNameListFinal;
priceListFinal;
discountListFinal;
discountRequestListFinal;




Since I'm using my custom tableViewCell class, I got this:

+ Show Spoiler +

@interface SearchResultTableViewCell : UITableViewCell

@property (strong, nonatomic) IBOutlet UILabel *price;
@property (strong, nonatomic) IBOutlet UILabel *itemName;
@property (strong, nonatomic) IBOutlet UILabel *discount;
@property (strong, nonatomic) IBOutlet UITextField *quantity;
@property (strong, nonatomic) IBOutlet UITextField *discountInput;

@end



Here are my cellForRowAtIndexPath and didSelectRowAtIndexPath methods

+ Show Spoiler +



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *ItemCellIdentifier = @"CellIdentifier";
SearchResultTableViewCell *tableCell =(SearchResultTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ItemCellIdentifier];


//set text labels here
[tableCell.price setText:[NSString stringWithString:[priceList objectAtIndex:indexPath.row]]];
[tableCell.itemName setText:[NSString stringWithString:[itemNameList objectAtIndex:indexPath.row]]];
[tableCell.discount setText:[NSString stringWithString:[discountList objectAtIndex:indexPath.row]]];
[tableCell.quantity setKeyboardType:UIKeyboardTypeDecimalPad];
[tableCell.discountInput setKeyboardType:UIKeyboardTypeDecimalPad];

tableCell.itemName.numberOfLines = 0;
tableCell.itemName.lineBreakMode = NSLineBreakByWordWrapping;

//set check mark and highlights.
if ([[checkList objectAtIndex:indexPath.row] integerValue] == 1){
tableCell.accessoryType = UITableViewCellAccessoryCheckmark;
[tableView selectRowAtIndexPath:indexPath
animated:YES
scrollPosition:UITableViewScrollPositionNone];

}
else{
tableCell.accessoryType = UITableViewCellAccessoryNone;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

return tableCell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

if ([[checkList objectAtIndex:indexPath.row] integerValue] == 1){
[checkList replaceObjectAtIndex:indexPath.row withObject:@"0"];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
else{
[checkList replaceObjectAtIndex:indexPath.row withObject:@"1"];
[tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
}

[self.searchResults reloadData];


}




And here is the part of the function that is killing me. I have no problem getting the item name, price, and default discount since those were taken from an array I created. My problem is that I could not access the tableRowCell properly and therefore, I can't access the textFields as well.

Here is my function so far. What I basically do is get the indexPaths of those rows that have been checked. Using that array of indices, I get the itemName, price, and discount from the arrays I initialised.

+ Show Spoiler +



-(void)prepareFinalArray{

itemNameListFinal = [[NSMutableArray alloc] init];
priceListFinal = [[NSMutableArray alloc] init];
discountListFinal = [[NSMutableArray alloc] init];
discountRequestListFinal = [[NSMutableArray alloc] init];

//this array keeps track of the indices
NSMutableArray *selectedItems = [[NSMutableArray alloc] init];

//loop at the checkList arrays, check which indices were checked.
for( int i = 0 ; i < [checkList count] ; i++ ){
if( [checkList[i] isEqualToString:@"1"] ){
NSNumber *currentElement = [NSNumber numberWithInteger:i];
NSLog(@"Selected item detected at %d,", i);
[selectedItems addObject:currentElement];
}
}

//Now that we have the index paths, get the itemNames, discount, user input qty, and user input discount.
for( int i = 0 ; i < [selectedItems count] ; i++){

[itemNameListFinal addObject:itemNameList[[[selectedItems objectAtIndex:i] integerValue]]];
[discountListFinal addObject:discountList[[[selectedItems objectAtIndex:i] integerValue]]];
}

}





And after that, I am pretty clueless on how to proceed. I know I can use the `cellForRowAtIndexPath` method, however, that returns a UITableViewCell object, and that's not he object I used since I had my own custom cell. Any ideas anyone?
"If i lost an arm, I would play w3." -IntoTheWow || "Member of Hyuk Hyuk Hyuk cafe. He's the next Jaedong, baby!"
Blisse
Profile Blog Joined July 2010
Canada3710 Posts
Last Edited: 2014-03-11 06:43:29
March 11 2014 06:42 GMT
#9069
You can cast your UITableViewCell to your SearchResultTableViewCell like so

SearchResultTableViewCell* cell = (SearchResultTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
There is no one like you in the universe.
SilverSkyLark
Profile Blog Joined April 2008
Philippines8437 Posts
Last Edited: 2014-03-11 08:20:01
March 11 2014 06:58 GMT
#9070
On March 11 2014 15:42 Blisse wrote:
You can cast your UITableViewCell to your SearchResultTableViewCell like so

SearchResultTableViewCell* cell = (SearchResultTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];

Wow. I can't believe I missed that one. Thank you.

EDIT

Sorry but I'm missing something simple again, how do I convert int to NSIndexPath? My app crashes at
SearchResultTableViewCell* cell = (SearchResultTableViewCell*)[searchResults cellForRowAtIndexPath:path];


because I force the int to indexPath conversion here:
NSIndexPath *path = [NSIndexPath indexPathWithIndex:i];


I'm looking around on how to convert int to NSUInteger and then NSIndexPath but I've yet to find anything.

Fixed with:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
"If i lost an arm, I would play w3." -IntoTheWow || "Member of Hyuk Hyuk Hyuk cafe. He's the next Jaedong, baby!"
Blisse
Profile Blog Joined July 2010
Canada3710 Posts
March 11 2014 11:26 GMT
#9071
Almost finished our small operating system on an ARM chip. I have to say it's really enjoyable coding like this. You basically know exactly what every part of the code is doing otherwise you won't really know how to code around in it. You can very easily tell who's a good coder and who's not so strong because you can't rely on custom language features to design your algorithms for you. And it's also really fun writing directly to memory addresses rather than letting the DMA do it for you. It's really fun and entertaining, though I wish we had more time to dive into the crazier stuff, like paging. I'm also interning for Microsoft on Outlook this summer, so that's nice too ^^
There is no one like you in the universe.
Manit0u
Profile Blog Joined August 2004
Poland17494 Posts
March 11 2014 13:52 GMT
#9072
On March 11 2014 11:38 Cyx. wrote:
Show nested quote +
On March 11 2014 11:06 Manit0u wrote:
On March 11 2014 07:15 RoyGBiv_13 wrote:
Feel free to ask any questions, however specific. I work at a C/C++ compiler company. Now I just need someone to ask a question regarding threads so I can pick up on how operating systems handle memory between multiple running programs.


I've got a question for you. Albeit it might be a stupid one since I'm just an amateur dabbler in programming for the most part and never learned the "behind the scenes" stuff as I never really needed that much knowledge. Well, now I'm interested in going deeper with my knowledge and want to apply better and more efficient practices when I write the code.

My question (please don't laugh if it's stupid):

int some_func(int num)
{
int x = num;

do stuff with x;

return x;
}


Is there any real difference if I pass the variable to the function, then assign the variable's value to another variable or if I work with the passed variable directly bar the readability?


int some_func(int num)
{
return (do stuff with num);
}


Note: I used simple int in the example, but what if that's actually an entire mapping or somesuch bigger data structure?


The only difference is that you make an extra copy in the first one ^^ The compiler makes a copy anyways when you pass by value like that, so unless the parameters are references, all you do is waste time (that the compiler probably optimizes away anyways).


Will it make any difference on a system that compiles stuff 'on the fly'? IE: you create your .c files and they get loaded as needed, which can be done at any time during the system/program uptime, you can add things to or change a working environment anytime you want.
Time is precious. Waste it wisely.
Cyx.
Profile Joined November 2010
Canada806 Posts
March 11 2014 14:42 GMT
#9073
On March 11 2014 22:52 Manit0u wrote:
Show nested quote +
On March 11 2014 11:38 Cyx. wrote:
On March 11 2014 11:06 Manit0u wrote:
On March 11 2014 07:15 RoyGBiv_13 wrote:
Feel free to ask any questions, however specific. I work at a C/C++ compiler company. Now I just need someone to ask a question regarding threads so I can pick up on how operating systems handle memory between multiple running programs.


I've got a question for you. Albeit it might be a stupid one since I'm just an amateur dabbler in programming for the most part and never learned the "behind the scenes" stuff as I never really needed that much knowledge. Well, now I'm interested in going deeper with my knowledge and want to apply better and more efficient practices when I write the code.

My question (please don't laugh if it's stupid):

int some_func(int num)
{
int x = num;

do stuff with x;

return x;
}


Is there any real difference if I pass the variable to the function, then assign the variable's value to another variable or if I work with the passed variable directly bar the readability?


int some_func(int num)
{
return (do stuff with num);
}


Note: I used simple int in the example, but what if that's actually an entire mapping or somesuch bigger data structure?


The only difference is that you make an extra copy in the first one ^^ The compiler makes a copy anyways when you pass by value like that, so unless the parameters are references, all you do is waste time (that the compiler probably optimizes away anyways).


Will it make any difference on a system that compiles stuff 'on the fly'? IE: you create your .c files and they get loaded as needed, which can be done at any time during the system/program uptime, you can add things to or change a working environment anytime you want.


I'll admit I'm not 100% sure what you mean - are you talking about just-in-time compiling C/C++? As far as I know that's not possible except with C++/CLI (in which case you're barely writing C++ anyways) and to some extent with LLVM (although by all accounts it isn't easy).

If you're wondering about other jitted languages, then I'm gonna say the only difference between a fully compiled language and a JIT compiled language in the code sample given was that a JIT compiler is LESS likely to optimize out the useless extra copy (since they're less willing to do optimizations overall) - but other than that, I'm pretty sure they'll try to do the same thing in principle. Don't quote me though.
RoyGBiv_13
Profile Blog Joined August 2010
United States1275 Posts
March 11 2014 17:13 GMT
#9074
On March 11 2014 23:42 Cyx. wrote:
Show nested quote +
On March 11 2014 22:52 Manit0u wrote:
On March 11 2014 11:38 Cyx. wrote:
On March 11 2014 11:06 Manit0u wrote:
On March 11 2014 07:15 RoyGBiv_13 wrote:
Feel free to ask any questions, however specific. I work at a C/C++ compiler company. Now I just need someone to ask a question regarding threads so I can pick up on how operating systems handle memory between multiple running programs.


I've got a question for you. Albeit it might be a stupid one since I'm just an amateur dabbler in programming for the most part and never learned the "behind the scenes" stuff as I never really needed that much knowledge. Well, now I'm interested in going deeper with my knowledge and want to apply better and more efficient practices when I write the code.

My question (please don't laugh if it's stupid):

int some_func(int num)
{
int x = num;

do stuff with x;

return x;
}


Is there any real difference if I pass the variable to the function, then assign the variable's value to another variable or if I work with the passed variable directly bar the readability?


int some_func(int num)
{
return (do stuff with num);
}


Note: I used simple int in the example, but what if that's actually an entire mapping or somesuch bigger data structure?


The only difference is that you make an extra copy in the first one ^^ The compiler makes a copy anyways when you pass by value like that, so unless the parameters are references, all you do is waste time (that the compiler probably optimizes away anyways).


Will it make any difference on a system that compiles stuff 'on the fly'? IE: you create your .c files and they get loaded as needed, which can be done at any time during the system/program uptime, you can add things to or change a working environment anytime you want.


I'll admit I'm not 100% sure what you mean - are you talking about just-in-time compiling C/C++? As far as I know that's not possible except with C++/CLI (in which case you're barely writing C++ anyways) and to some extent with LLVM (although by all accounts it isn't easy).

If you're wondering about other jitted languages, then I'm gonna say the only difference between a fully compiled language and a JIT compiled language in the code sample given was that a JIT compiler is LESS likely to optimize out the useless extra copy (since they're less willing to do optimizations overall) - but other than that, I'm pretty sure they'll try to do the same thing in principle. Don't quote me though.


A function such as this would likely be inlined by the compiler, meaning that the compiler would try to remove the function altogether, the stack generation and branch to the function. In its place, anywhere that the function is called would just be replaced with the code generated for (do stuff to num). Of course, this isn't the entire answer. Lets break down the original function and see what a compiler might do:


int some_func(int num)
{
int x = num;

do stuff with x;

return x;
}


First off, the compiler will notice that there is no conditions or loops in this, so that the entire function fits within one "basic block". If any code is executed in a basic block, the entire block is guaranteed to be executed. Secondly, the compiler can recognize temporary variables, such as x. Depending on your usage of x, it may try to work backwards from all the points x is used, and tries to fill in num. If that works without any problems, then it will optimize away x entirely. Going through the first pass optimization pass of the compiler, it may look like your second code block:


int some_func(int num)
{
return (do stuff with num);
}


The compiler might then look at this basic function, and decide that it doesn't need to branch all the way to some other place in memory and setup a new stack in order to find a return value. Instead of generating assembly equating to "branch to some_func, then pop the first value in the stack off into a register as the return value", it will instead replace it with "do some stuff with register where num is, then return that as the value to be used". This, as I mentioned earlier, is called "inlining", and can be explicitly suggested to the compiler using a keyword, usually. In GCC, it's __inline__:


int __inline__ some_func(int num)


This isn't mandatory, as the compiler will likely inline functions like this anyway.

The question about how will functions like this be handled in Just-In-Time compilation depends on the system in which you're running your code. Native C cannot be run JIT, as it is a strictly compiled language, but if its running in a virtualized system, the system could read the C code and execute instructions based on it. The level of optimizations that the virtual system goes through in running the C code depends on the virtual system.

Note that it is quite possible to compiler C/C++ code into its object code and then link that against a dynamic setting, such as .dll's for Windows or .so for linux, which can be ran dynamically, but thats a whole different thing than JIT compiling.
Any sufficiently advanced technology is indistinguishable from magic
Manit0u
Profile Blog Joined August 2004
Poland17494 Posts
Last Edited: 2014-03-11 18:20:43
March 11 2014 18:14 GMT
#9075
I guess I should explain the "on the fly" compilation I mentioned. It's a mudlib gamedriver. It runs perpetually for two weeks non-stop with players running around etc. Every object there is loaded and compiled when required (ex: when a player enters the location object or interacts with other objects - everything is an object there). The coders have dual-acces, both as GM's in the game, where they can view all the code and even edit it from inside the game (it's a bit tricky though as the only editor available there is ed) and regular ftp server acces. The GMs can load/destruct/update all objects from within the game. You can change everything on the fly (when a bug occurs for example and needs to be fixed quickly) without having to pre-compile anything and it will be fully functional. You can add new stuff or modify existing stuff in the game even while it's running simply by adding/editing .c files.

I'm not entirely sure about the underlying technology since I'm too newb at it still. Here you can view the gamedriver itself:
https://github.com/cotillion/cd-gamedriver

Here's some info on how the stack works in it. It appears it's using some form of virtual stacks:
https://github.com/cotillion/cd-gamedriver/blob/master/doc/STACKMACHINE
Time is precious. Waste it wisely.
Cyx.
Profile Joined November 2010
Canada806 Posts
Last Edited: 2014-03-11 23:50:08
March 11 2014 23:47 GMT
#9076
On March 12 2014 03:14 Manit0u wrote:
I guess I should explain the "on the fly" compilation I mentioned. It's a mudlib gamedriver. It runs perpetually for two weeks non-stop with players running around etc. Every object there is loaded and compiled when required (ex: when a player enters the location object or interacts with other objects - everything is an object there). The coders have dual-acces, both as GM's in the game, where they can view all the code and even edit it from inside the game (it's a bit tricky though as the only editor available there is ed) and regular ftp server acces. The GMs can load/destruct/update all objects from within the game. You can change everything on the fly (when a bug occurs for example and needs to be fixed quickly) without having to pre-compile anything and it will be fully functional. You can add new stuff or modify existing stuff in the game even while it's running simply by adding/editing .c files.

I'm not entirely sure about the underlying technology since I'm too newb at it still. Here you can view the gamedriver itself:
https://github.com/cotillion/cd-gamedriver

Here's some info on how the stack works in it. It appears it's using some form of virtual stacks:
https://github.com/cotillion/cd-gamedriver/blob/master/doc/STACKMACHINE


Sounds basically like just-in-time compilation, which is the same thing that you can use in some scripting languages (Lua, Python etc...) when you don't want the overhead of running your code through an interpreter all the time ^^

e: so I guess I should tell you guys how my 'command line interview' went... it was not as complex as previously thought, I just had to write a couple of scripts and fix some bugs in some stuff. It was on the command line on Ubuntu so all the stuff I had been worrying about for the last couple days was still pretty useful, but I didn't have to know how to grep anything or anything dumb like that ^^
Shield
Profile Blog Joined August 2009
Bulgaria4824 Posts
Last Edited: 2014-03-11 23:49:04
March 11 2014 23:47 GMT
#9077
I am looking to learn some good Java coding practices. Has anyone here published their source code publicly? If yes, can I have a link please to have a look. Objective-C/OOP C++ may also help although I am not that familiar with C++'s syntax. I know a bit of C though.
Manit0u
Profile Blog Joined August 2004
Poland17494 Posts
March 12 2014 00:40 GMT
#9078
On March 12 2014 08:47 Cyx. wrote:
Show nested quote +
On March 12 2014 03:14 Manit0u wrote:
I guess I should explain the "on the fly" compilation I mentioned. It's a mudlib gamedriver. It runs perpetually for two weeks non-stop with players running around etc. Every object there is loaded and compiled when required (ex: when a player enters the location object or interacts with other objects - everything is an object there). The coders have dual-acces, both as GM's in the game, where they can view all the code and even edit it from inside the game (it's a bit tricky though as the only editor available there is ed) and regular ftp server acces. The GMs can load/destruct/update all objects from within the game. You can change everything on the fly (when a bug occurs for example and needs to be fixed quickly) without having to pre-compile anything and it will be fully functional. You can add new stuff or modify existing stuff in the game even while it's running simply by adding/editing .c files.

I'm not entirely sure about the underlying technology since I'm too newb at it still. Here you can view the gamedriver itself:
https://github.com/cotillion/cd-gamedriver

Here's some info on how the stack works in it. It appears it's using some form of virtual stacks:
https://github.com/cotillion/cd-gamedriver/blob/master/doc/STACKMACHINE


Sounds basically like just-in-time compilation, which is the same thing that you can use in some scripting languages (Lua, Python etc...) when you don't want the overhead of running your code through an interpreter all the time ^^

e: so I guess I should tell you guys how my 'command line interview' went... it was not as complex as previously thought, I just had to write a couple of scripts and fix some bugs in some stuff. It was on the command line on Ubuntu so all the stuff I had been worrying about for the last couple days was still pretty useful, but I didn't have to know how to grep anything or anything dumb like that ^^


But grep is awesome... I have no idea how people can do anything other than gaming on Windows. I feel lost without console and I barely ever use a mouse aside from gaming. And the fact that you can combine commands in Linux terminal (especially with grep) is also amazing. You can for example get through entire file and write lines that contain certain pattern into another file all with one command. Hell, you can even get entire file sections thrown out onto your screen/written to another file or get a listing of all files containing the pattern etc.

On March 12 2014 08:47 darkness wrote:
I am looking to learn some good Java coding practices. Has anyone here published their source code publicly? If yes, can I have a link please to have a look. Objective-C/OOP C++ may also help although I am not that familiar with C++'s syntax. I know a bit of C though.


http://cc2e.com/Default.aspx

Get this book.
Time is precious. Waste it wisely.
klo8
Profile Joined August 2010
Austria1960 Posts
Last Edited: 2014-03-12 00:51:54
March 12 2014 00:49 GMT
#9079
On March 12 2014 08:47 darkness wrote:
I am looking to learn some good Java coding practices. Has anyone here published their source code publicly? If yes, can I have a link please to have a look. Objective-C/OOP C++ may also help although I am not that familiar with C++'s syntax. I know a bit of C though.

If you're willing to read a book, this is the one to get: http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683
It does not address the changes made in Java 7 or 8 but the fundamentals of the language have not changed since the book was published.

I'm reluctant to post code I wrote because I'm not a great Java programmer, but if you really want to, you can take a look at this emulator for a toy processor architecture (Micro16) I wrote last week. It does not showcase advanced Java features very much, no concurrency or parallelism or anything of the sort.

https://github.com/GyrosOfWar/Micro16

edit: Guy above me recommended Clean Code, which I haven't read yet, but from what I've heard it's a really good book. Effective Java is obviously a lot more specific to Java and OOP, but I think it teaches good coding practices in general as well.
This post is clearly not a hurr, as you can see from the graph, the durr never intersects with the derp.
berated-
Profile Blog Joined February 2007
United States1134 Posts
March 12 2014 01:01 GMT
#9080
On March 12 2014 09:49 klo8 wrote:
Show nested quote +
On March 12 2014 08:47 darkness wrote:
I am looking to learn some good Java coding practices. Has anyone here published their source code publicly? If yes, can I have a link please to have a look. Objective-C/OOP C++ may also help although I am not that familiar with C++'s syntax. I know a bit of C though.

If you're willing to read a book, this is the one to get: http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683
It does not address the changes made in Java 7 or 8 but the fundamentals of the language have not changed since the book was published.

I'm reluctant to post code I wrote because I'm not a great Java programmer, but if you really want to, you can take a look at this emulator for a toy processor architecture (Micro16) I wrote last week. It does not showcase advanced Java features very much, no concurrency or parallelism or anything of the sort.

https://github.com/GyrosOfWar/Micro16

edit: Guy above me recommended Clean Code, which I haven't read yet, but from what I've heard it's a really good book. Effective Java is obviously a lot more specific to Java and OOP, but I think it teaches good coding practices in general as well.


+1 for clean code. its also java oriented but can be applied to other languages. I've been a software dev as a professional for 6 years almost and just read the book this weekend. I feel fortunate I was able to grow and experience a lot of things organically but I wish I would have read the book when I started.

I read it on kindle but went and bought 2 hard copies to take to my other colleagues before I was even halfway through the book. thanks to everyone in this thread who recommended it.
Prev 1 452 453 454 455 456 1032 Next
Please log in or register to reply.
Live Events Refresh
StarCraft2.fi
17:00
15V Cup / Groups Day 3
starcraft2fi 104
Reevou 12
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
LamboSC2 465
Fuzer 329
Livibee 96
gerald23 88
SpeCial 87
BRAT_OK 83
MindelVK 16
StarCraft: Brood War
Calm 3096
Shuttle 1050
Mini 757
EffOrt 503
Larva 235
Dewaltoss 101
hero 99
Aegong 25
Rock 21
Dota 2
Gorgc5902
qojqva4341
Dendi1165
syndereN396
Counter-Strike
zeus10906
chrisJcsgo73
edward28
kRYSTAL_23
Other Games
DeMusliM2139
FrodaN902
hiko759
Hui .125
KnowMe95
QueenE94
Trikslyr64
ViBE4
Organizations
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 15 non-featured ]
StarCraft 2
• Kozan
• AfreecaTV YouTube
• intothetv
• sooper7s
• IndyKCrew
• LaughNgamezSOOP
• Migwel
StarCraft: Brood War
• 3DClanTV 8
• FirePhoenix6
• STPLYoutube
• ZZZeroYoutube
• BSLYoutube
Dota 2
• WagamamaTV633
League of Legends
• TFBlade1080
Other Games
• Shiphtur134
Upcoming Events
Replay Cast
5h 58m
The PondCast
15h 58m
OSC
21h 58m
Demi vs Mixu
Nicoract vs TBD
Babymarine vs MindelVK
ForJumy vs TBD
Shameless vs Percival
Replay Cast
1d 5h
Korean StarCraft League
2 days
CranKy Ducklings
2 days
WardiTV 2025
2 days
SC Evo League
2 days
BSL 21
3 days
Sziky vs OyAji
Gypsy vs eOnzErG
OSC
3 days
Solar vs Creator
ByuN vs Gerald
Percival vs Babymarine
Moja vs Krystianer
EnDerr vs ForJumy
sebesdes vs Nicoract
[ Show More ]
Sparkling Tuna Cup
3 days
WardiTV 2025
3 days
OSC
3 days
BSL 21
4 days
Bonyth vs StRyKeR
Tarson vs Dandy
Replay Cast
4 days
Wardi Open
4 days
StarCraft2.fi
4 days
Monday Night Weeklies
4 days
Replay Cast
5 days
WardiTV 2025
5 days
StarCraft2.fi
5 days
PiGosaur Monday
6 days
StarCraft2.fi
6 days
Liquipedia Results

Completed

Proleague 2025-11-30
RSL Revival: Season 3
Light HT

Ongoing

C-Race Season 1
IPSL Winter 2025-26
KCM Race Survival 2025 Season 4
YSL S2
BSL Season 21
CSCL: Masked Kings S3
Slon Tour Season 2
Acropolis #4 - TS3
META Madness #9
SL Budapest Major 2025
ESL Impact League Season 8
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2

Upcoming

BSL 21 Non-Korean Championship
Acropolis #4
IPSL Spring 2026
Bellum Gens Elite Stara Zagora 2026
HSC XXVIII
RSL Offline Finals
WardiTV 2025
Kuram Kup
PGL Cluj-Napoca 2026
IEM Kraków 2026
BLAST Bounty Winter 2026
BLAST Bounty Winter Qual
eXTREMESLAND 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...

Disclosure: This page contains affiliate marketing links that support TLnet.

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.