• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

upandaway

Member
It's such a surreal feeling to run thousands of lines of tests I got for the homework assignment and see them all work.

Like that literally never happens. I'm suspecting the tests themselves are just broken too.
 

NotBacon

Member
check variable contains a value that it's comparing with the contents in the list. I understand the description but not sure on how to do it. So we use nested for loops to do it?

Take it one step at a time. Break the big problem down into little problems.

Notes:

- You need to make a list somewhere. Do that first and fill it (another function) with some random values.
- Make your check_list function also take in a LL header node. Pass in the header node from the LL you made before.
- Loop through the nodes (the current = current->next stuff) and look at the data inside each node, not the index of the node.
 

0xCA2

Member
Speaking of jobs, my last couple of interviews haven't panned out, and I have one tomorrow that I haven't really planned for (mostly from putting it off due to lack of confidence) . Job searching can be really draining. My school has some good student programming job opportunities but I feel like I don't have the skills to crack the interview right now (these aren't even technical interviews, just regular interviews). I just have to keep banging my head up against it until I get it right.

I know it takes practice but it just sucks to fuck up good opportunities, especially when the major is getting crowded now (at least at my school) and I need as much experience I can get ASAP.
Edit; today's interview was actually my best yet. I don't expect to get the job but I think I'm getting better at this.
 
Can I PM someone my code, because I'm trying to print out a numbers that's in a list. But doesn't work. Similar problem with checking if a value exist. There's a while loop in ostream operator function and in check_list that checks if the list is not empty. It skips the code within a while loop, and goes to the return statement.
 

Water

Member
Is this book geared towards devs that are already really familiar with the language up till '11/'14?

Table of contents says "yes". At a glance, everything seems to be about the new stuff.

And besides, Meyers is a very incisive guy and the language is very fiddly. I think pretty much everyone who works with the language, no matter how experienced, can take away something from his classic Effective C++ books. You've already read them, I presume?
 
Is this book geared towards devs that are already really familiar with the language up till '11/'14?

Yeah, it's not an intro to C++ book at all. As someone that was basically taught C++98 (which is merely a superset of C mind you!) though, this really shines a light on what makes modern C++ good.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Table of contents says "yes". At a glance, everything seems to be about the new stuff.

And besides, Meyers is a very incisive guy and the language is very fiddly. I think pretty much everyone who works with the language, no matter how experienced, can take away something from his classic Effective C++ books. You've already read them, I presume?

Nope, I haven't. My C++ is shaky at best, so I was more interested in if those books would be a good place to improve it. I'll look elsewhere.
 
Can I PM someone my code, because I'm trying to print out a numbers that's in a list. But doesn't work. Similar problem with checking if a value exist. There's a while loop in ostream operator function and in check_list that checks if the list is not empty. It skips the code within a while loop, and goes to the return statement.

I think people are generally more receptive to commenting on code that is posted here, rather than answering questions through PMs. If you're worried that it's because of a homework assignment, then only paste in a few lines relevant to your question, and remove any extraneous stuff, and change names to foo and bar or something.

In any case, in this instance it sounds to me like your list is empty. You should inspect the code that you think is adding items to the list. You should also try using a debugger.

Sadly I think 99% of homework questions could be answered with "use a debugger", it amazes me that they don't teach basic debugging skills in the first couple weeks of a programming course. Not really your fault that you haven't been taught how to use a debugger, but really, any problem you could possibly encounter in your first year or so of taking programming courses can be solved very easily by "set breakpoint, run program, step, print value, step, print value, etc until something isn't what you expect"
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
I've never gone through a single class that explains error checking or debugging processes. Blows me away that they don't have that as an entry level course. It should at least be integrated into a curriculum.
 

Two Words

Member
So I hit an odd situation with recursive function. The following code below should not work, but it does. The recursive call is not part of a return statement. That means that when the recursive function spins back, nothing is being returned. Somehow this works and gives you the proper sum. In main, you want to write something like int sum = recursiveSum(5, 10); and if you output the amount of sum, you will see 15.

Code:
int recursiveSum(int num1, int num2)
{
   if (num2 == 0)
       return num1;
   else
   {
       if (num2 < 0)
       {
           num2++;
           num1--;
           recursiveSum(num1,num2);
       }
       else
       {
           num2--;
           num1++;
           recursiveSum(num1, num2);
       }
   }
}

However, adding a cout statement recursive call statements gives you extremely erroneous results. Can anybody explain?
 
I think people are generally more receptive to commenting on code that is posted here, rather than answering questions through PMs. If you're worried that it's because of a homework assignment, then only paste in a few lines relevant to your question, and remove any extraneous stuff, and change names to foo and bar or something.

In any case, in this instance it sounds to me like your list is empty. You should inspect the code that you think is adding items to the list. You should also try using a debugger.

Sadly I think 99% of homework questions could be answered with "use a debugger", it amazes me that they don't teach basic debugging skills in the first couple weeks of a programming course. Not really your fault that you haven't been taught how to use a debugger, but really, any problem you could possibly encounter in your first year or so of taking programming courses can be solved very easily by "set breakpoint, run program, step, print value, step, print value, etc until something isn't what you expect"

I debugged the program, and your right. The list is empty though I called insertion function before attempting to print the list. I'm not sure why though.
 

Haly

One day I realized that sadness is just another word for not enough coffee.

Haly

One day I realized that sadness is just another word for not enough coffee.
But that example shows that it works, not that you get the right results. Somehow, if you add 1 + 4, that function is managing to return 5, not 0.
Your code here:
Code:
else
{
     num2--;
     num1++;
     recursiveSum(num1, num2);
}

Actually operates like this when it's compiled and ran:
Code:
else
{
     num2--;
     num1++;
     return recursiveSum(num1, num2);
}
Which is how that function should be written and exhibits the correct behavior.
 

Two Words

Member
Your code here:
Code:
else
{
     num2--;
     num1++;
     recursiveSum(num1, num2);
}

Actually operates like this when it's compiled and ran:
Code:
else
{
     num2--;
     num1++;
     return recursiveSum(num1, num2);
}
Which is how that function should be written and exhibits the correct behavior.
But how does it know to return that and not simply return zero? Also, why does it give a wrong result of you add a cout statement after that recursive call, but not other things like assignments or declarations?
 
But how does it know to return that and not simply return zero? Also, why does it give a wrong result of you add a cout statement after that recursive call, but not other things like assignments or declarations?

On x86 architectures, the return value is typically stored in the EAX register. That's just by convention, and how most compilers generate code. When you write this:

Code:
int foo() {
    return 7;   // (1)
}

int main() {
    int f = foo();  // (2)
    cout << f;
}

The statement at (1) is executing these assembly instructions:

Code:
mov eax, 7;
ret;

And the statement at (2) is executing these instructions:

Code:
call <address of foo()>;      // Call the function foo()
mov <address of f>, eax;   // Mov the return value of foo() into the variable f
// Push arguments for the call to operator <<
push eax;                         // Normally this would load it from a register, but compiler is smart enough to know that even though the argument is the variable "f", the register 'eax" contains the same value at this particualr moment.
push cout;
call < address of basic_iostream::operator<<() >  // call basic_ostream::operator <<(cout, f);   // The first argument to a member function is the "this" pointer, which in this case is the instance 'cout'

The important thing to note is that the main() and foo() both "agree" that the return value will be in eax, so they just know to look there.

Look at just this part fo your function:
Code:
if (num2 == 0)
    return num1;

What this is really doing is saying this:
Code:
// Semi pseudocode to avoid unimportant details of assembly language
if (num2 == 0) {
    __asm mov eax, num1;   // Move the value of num1 into EAX register
    __asm ret;           // Exit the function.
}
When you call recursiveSum, eventually it will boil down to those assembly instructions, at which point EAX contains the correct return value. All it does from that point is unwind out of recursive calls. No other instructions ever get executed, so nothing else has the potential to modify EAX and eventually you unwind all the way out back up to main. EAX still has the same value in it as it did when it mov'ed num1 into it, and so main just thinks that's what the return value was.

Edit: And it gives a wrong value when you add a cout() call because cout returns a value, which modifies eax. Try this:

Code:
int recursiveSum(int num1, int num2)
{
   if (num2 == 0)
       return num1;
   else
   {
       if (num2 < 0)
       {
           num2++;
           num1--;
           recursiveSum(num1,num2);
       }
       else
       {
           num2--;
           num1++;
           recursiveSum(num1, num2);
       }
   }
#if defined(_MSC_VER)        // Microsoft Visual C++
   __asm mov eax, 1234567
#else                        // Everything else
   __asm__("movl $1234567, %eax")
#endif
}

and see what happens
 
Can you post the line of code that does the insertion, followed by the line(s) that print?

Code:
void fooLists::fooInsert(int pos, const itemlists& new_item)throw(OutOfRangeException, listexception){
	int new_size = getSize() + 1;
	if((pos < 1) || (pos > new_size)){
		throw OutOfRangeException("You can't insert an item when you're out of range!");
	} else {
		try{
			Node *new_pointer = new Node;
			size = new_size;
			new_pointer->item = new_item;
			
			if(pos == 1 ){ //Attach a new node at the beginning of a list.
				new_pointer->next = head; //Insert a new node to the list.
				head = new_pointer;
			} else {
				Node *previous = find(pos-1);
				new_pointer->next = previous->next;
				previous->next = new_pointer;
			}
		} 
		
		catch(bad_alloc e){
			throw listexception("Failed to insert a new node!");
		}
	}
	
}

ostream &operator<<(ostream &output, const fooLists &list){
	fooLists list1;
	list1.head = list.head;
	
	while(list1.head != NULL){
		if(list1.head->next == NULL){
			output << list1.head->item;
			list1.head = list1.head->next;
		} else{
			output << list1.head->item << ", ";
			list1.head = list1.head->next;
		}
	}
	return output;
}
 
Why are there so many semicolons? Especially in the function declaration and if statements.

EDIT: Wow, so the code viewer on mobileGaf inserts lots of extra characters that aren't on the page itself. That's quite the bug.
 

Two Words

Member
On x86 architectures, the return value is typically stored in the EAX register. That's just by convention, and how most compilers generate code. When you write this:

Code:
int foo() {
    return 7;   // (1)
}

int main() {
    int f = foo();  // (2)
    cout << f;
}

The statement at (1) is executing these assembly instructions:

Code:
mov eax, 7;
ret;

And the statement at (2) is executing these instructions:

Code:
call <address of foo()>;      // Call the function foo()
mov <address of f>, eax;   // Mov the return value of foo() into the variable f
// Push arguments for the call to operator <<
push eax;                         // Normally this would load it from a register, but compiler is smart enough to know that even though the argument is the variable "f", the register 'eax" contains the same value at this particualr moment.
push cout;
call < address of basic_iostream::operator<<() >  // call basic_ostream::operator <<(cout, f);   // The first argument to a member function is the "this" pointer, which in this case is the instance 'cout'

The important thing to note is that the main() and foo() both "agree" that the return value will be in eax, so they just know to look there.

Look at just this part fo your function:
Code:
if (num2 == 0)
    return num1;

What this is really doing is saying this:
Code:
// Semi pseudocode to avoid unimportant details of assembly language
if (num2 == 0) {
    __asm mov eax, num1;   // Move the value of num1 into EAX register
    __asm ret;           // Exit the function.
}
When you call recursiveSum, eventually it will boil down to those assembly instructions, at which point EAX contains the correct return value. All it does from that point is unwind out of recursive calls. No other instructions ever get executed, so nothing else has the potential to modify EAX and eventually you unwind all the way out back up to main. EAX still has the same value in it as it did when it mov'ed num1 into it, and so main just thinks that's what the return value was.

Edit: And it gives a wrong value when you add a cout() call because cout returns a value, which modifies eax. Try this:

Code:
int recursiveSum(int num1, int num2)
{
   if (num2 == 0)
       return num1;
   else
   {
       if (num2 < 0)
       {
           num2++;
           num1--;
           recursiveSum(num1,num2);
       }
       else
       {
           num2--;
           num1++;
           recursiveSum(num1, num2);
       }
   }
#if defined(_MSC_VER)        // Microsoft Visual C++
   __asm mov eax, 1234567
#else                        // Everything else
   __asm__("movl $1234567, %eax")
#endif
}

and see what happens
I see. Wow, that is a very in depth explanation.
 
I might be overlooking something, but both of these functions look fine to me. Well, style wise they could be improved a bit, but behavior wise they look like they should do the right thing. What does the line look like that calls insert and operator<<?

It looks like the line runs normally, but for operator<< it skips the while statement. The compiler thinks it's empty. I'm not sure what to do at this point. I've debugged, and know the reason why it's not printing the list. But I can't retrace the problem since we're using pointers.
 
It looks like the line runs normally, but for operator<< it skips the while statement. The compiler thinks it's empty. I'm not sure what to do at this point. I've debugged, and know the reason why it's not printing the list. But I can't retrace the problem since we're using pointers.

Can you post the lines of code that call insert and operator <<?
 

upandaway

Member
I've never gone through a single class that explains error checking or debugging processes. Blows me away that they don't have that as an entry level course. It should at least be integrated into a curriculum.
We had one lecture in Intro for debugging and one lecture in OOP for errors, that's it I think. Actually most of the people new to programming I saw use debugging quite a bit, I never bothered.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
I've never properly learned debugging tools myself yet. It's on my list of things to learn. Dealing with JavaScript primarily I usually rely on console logs or Chrome devtools for error help. But I'd like to learn the proper way sometime.

We had one lecture in Intro for debugging and one lecture in OOP for errors, that's it I think. Actually most of the people new to programming I saw use debugging quite a bit, I never bothered.

I've taken four "intro" programming courses as a result of school transfer mixups. The first school was heavy on OOP principles in Java. Second school barely even discussed OOP concepts outside of mentioning what a class was in C++. Kinda sad, because a lot of my classmates don't understand proper OOP stuff.
 
D

Deleted member 30609

Unconfirmed Member
I'm SEng postgrad helping with some curriculum restructuring, and we really, really had to fight to get a testing/QA module into the second year course map.
 

upandaway

Member
I've been away from C for about 4 months now and got an assignment in data structures about graphs to do in C.

I've come around to C and I like it, but heck man. Why do this to me. I've spent about 4 hours now on this Data Structures assignment doing nothing related to DS, just trying to deal with the input string.

If I finish this assignment and find a null pointer error I'll probably break down
 

Ambitious

Member
Working on a JSF-based web app for a university project. In addition to standard username/password authentication (which we already implemented), users should be able to sign in using Facebook or Twitter. It should be easy to extend it with additional providers.
Could someone recommend me a framework for this?

I've had a look at Spring Social, Scribe and SocialAuth.

Spring Social is of course the most powerful of those three, but jesus, it's incredibly complex, at least from what I've seen so far.
Scribe looks pretty simple to use, but apparently it only returns an access token after signing. SS, on the other hand, provides a uniform way (independent of the provider) to obtain personal data like name, email, username and so on.
SocialAuth appears to be kinda in the middle between the other two, in terms of complexity and features. But there's a suspicious lack of comments/impressions about it, and not many stars/watchers on GitHub either.

I'd really appreciate some help, because the way it looks, I'm probably gonna be the one responsible for implementing this.
 

wolfmat

Confirmed Asshole
Working on a JSF-based web app for a university project. In addition to standard username/password authentication (which we already implemented), users should be able to sign in using Facebook or Twitter. It should be easy to extend it with additional providers.
Could someone recommend me a framework for this?

I've had a look at Spring Social, Scribe and SocialAuth.

Spring Social is of course the most powerful of those three, but jesus, it's incredibly complex, at least from what I've seen so far.
Scribe looks pretty simple to use, but apparently it only returns an access token after signing. SS, on the other hand, provides a uniform way (independent of the provider) to obtain personal data like name, email, username and so on.
SocialAuth appears to be kinda in the middle between the other two, in terms of complexity and features. But there's a suspicious lack of comments/impressions about it, and not many stars/watchers on GitHub either.

I'd really appreciate some help, because the way it looks, I'm probably gonna be the one responsible for implementing this.
I'd recommend starting here, and getting a good look at the official docs, before looking at frameworks -- you won't know what's what otherwise: https://developers.facebook.com/docs/graph-api
(1) You'll need an app https://developers.facebook.com/apps/
(2) Facebook users sign into the app, the access tokens are associated with it
(3) If you need info for a user, you can just request it as the Graph API dictates (provided it falls into the granted auth scope)
That is the rudimentary connection between your app and a Facebook user. The framework doesn't usually explain how this works. Read the API docs, at least the surface stuff. That'll help a LOT.

Edit: Sorry, didn't remember when posting that you wanted to incorporate other APIs as well.
I've evaluated the top Google results for "Social Login framework" a while ago for work stuff, and after seeing inconsistencies and slow adoption rates with newer versions of the APIs, we've decided that it's best to either do it by hand, or not do it at all. Recently (April 30th), Facebook for example made Graph API 2.0 the minimum API version, but my evaluation run was somewhen in December 2014, and the frameworks I had evaluated often hadn't adapted to the new API yet although that was already useable at that point. We've prepared the switch by hand and saw issues in other developers' projects, and I assume they've had to deal with slow adoption.
Same thing happened with Twitter when they made v1.1 minimum. Lots of frameworks hadn't even considered OAuth2 at that point.

You might HAVE to incorporate a framework for your task because it's too complex otherwise, but it might end up being uncomfortable in some cases. That's what I'm saying.
Before opening up to a social network in terms of login, check that the framework you're using has kept up with recent developments of the related APIs.

Sorry I can't be more helpful regarding the frameworks you've picked. Didn't read properly, I have to admit that wasn't okay.
 

Ambitious

Member
I'd recommend starting here, and getting a good look at the official docs, before looking at frameworks -- you won't know what's what otherwise: https://developers.facebook.com/docs/graph-api
(1) You'll need an app https://developers.facebook.com/apps/
(2) Facebook users sign into the app, the access tokens are associated with it
(3) If you need info for a user, you can just request it as the Graph API dictates (provided it falls into the granted auth scope)
That is the rudimentary connection between your app and a Facebook user. The framework doesn't usually explain how this works. Read the API docs, at least the surface stuff. That'll help a LOT.

Thanks, but I know how OAuth works. I'm just not sure which framework is best suited for our application. As I mentioned in my previous post, it should be easy to add new providers, but at the very least we need to support Facebook and Twitter.

However, there's something I haven't figured out about OAuth: How exactly are the credentials of OAuth users usually persisted? Like, someone signs in to our app using a Twitter account. We obtain an access token and can use it to get their credentials (id, name, email) and create a User object for that. What now? To my knowledge, we should persist the user's id, not the access token. That way, if Twitter ever returns a different token when the user signs in again, we are still able to find their local account (the item from the User table). Is that how it's done?
 

wolfmat

Confirmed Asshole
Thanks, but I know how OAuth works. I'm just not sure which framework is best suited for our application. As I mentioned in my previous post, it should be easy to add new providers, but at the very least we need to support Facebook and Twitter.

However, there's something I haven't figured out about OAuth: How exactly are the credentials of OAuth users usually persisted? Like, someone signs in to our app using a Twitter account. We obtain an access token and can use it to get their credentials (id, name, email) and create a User object for that. What now? To my knowledge, we should persist the user's id, not the access token. That way, if Twitter ever returns a different token when the user signs in again, we are still able to find their local account (the item from the User table). Is that how it's done?

No you should persist the access token if you want to make further requests, and it'll eventually expire, at which point you're supposed to demand an access token again if you want to update user data. That's what the token is for (making requests in the name of the related user in the context of your app).

Of course you should persist the User ID -- this is what enables persistence. The access token will make it possible to login the user via Facebook, and log him in again once he's killed his cookies or whatever. Check the Graph API Explorer, for example, when you query /me: https://developers.facebook.com/tools/explorer/?method=GET&path=me&version=v2.3& -- you obtain an app-scoped user ID, which you can look up in your DB and it's good.

So social login works like this, in an abstract manner:
- Obtain the access token (login with POST-back or whatever)
- Query the token's owner at the platform
- Store ID and other stuff, but also the token if you want to make requests in his name without him being on the site
- User's browser gets his cookie, the cookie builds the session when viewing
- The cookie of course relates the viewer to your DB entry
- If applicable, refresh the token autonomously (not all platforms support this; Google+ does, for example)

So if the cookie is gone, you start the same sequence (demand access token), but as soon as the token owner is identified and you discover him in your database, you can build his environment as it was when he last manipulated data or whatever.
 

tariniel

Member
I saw an article "Five programming problems every Software Engineer should be able to solve in less than 1 hour". I wrote the following three functions for question 1: "Write three functions that compute the sum of the numbers in a given list using a for-loop, a while-loop, and recursion.".

How could I write these better, or optimize them better?

Code:
        public static int sumOfListFor(List<int> numbers)
        {
            int sum = 0;
            foreach(int number in numbers)
            {
                sum += number;
            }
            return sum;

        public static int sumOfListWhile(List<int> numbers)
        {
            int sum = 0;
            int counter = 0;

            while(counter < numbers.Count)
            {
                sum += numbers[counter];
                counter++;
            }

            return sum;
        }

        public static int sumOfListRecursive(List<int> numbers)
        {
            if (numbers.Count == 0)
            {
                return 0;
            }
            else
            {
                int sum = 0;
                sum += numbers[0];
                numbers.RemoveAt(0);
                return sum + sumOfListRecursive(numbers);
            }
        }
 
I saw an article "Five programming problems every Software Engineer should be able to solve in less than 1 hour". I wrote the following three functions for question 1: "Write three functions that compute the sum of the numbers in a given list using a for-loop, a while-loop, and recursion.".

How could I write these better, or optimize them better?

Code:
        public static int sumOfListFor(List<int> numbers)
        {
            int sum = 0;
            foreach(int number in numbers)
            {
                sum += number;
            }
            return sum;

        public static int sumOfListWhile(List<int> numbers)
        {
            int sum = 0;
            int counter = 0;

            while(counter < numbers.Count)
            {
                sum += numbers[counter];
                counter++;
            }

            return sum;
        }

        public static int sumOfListRecursive(List<int> numbers)
        {
            if (numbers.Count == 0)
            {
                return 0;
            }
            else
            {
                int sum = 0;
                sum += numbers[0];
                numbers.RemoveAt(0);
                return sum + sumOfListRecursive(numbers);
            }
        }

For the 3rd, pass the current index into the function, you can write the entire function in 1 line that way.
 

Chris R

Member
My solution to question 5 isn't elegant, but it works and I was able to do it in under an hour.

Write a program that outputs all possibilities to put + or - or nothing between the numbers 1, 2, ..., 9 (in this order) such that the result is always 100. For example: 1 + 2 + 34 – 5 + 67 – 8 + 9 = 100.

I probably would come back to it and find a solution that would work on a bigger problem space if it wasn't just a simple little challenge thing, but for a small number brute force worked.
 

Saprol

Member
The guy writing comes off as an ass, but the problems are worth the read.

If you bother to read this blog at all (or any other blog about software development), you are probably good enough to solve these and 5 more problems within the hour. The people that think are above all these "nonsense" are usually the ones that can't code crap.

reddit said:
Well this asshole should stop calling himself a software engineer, since his solution for #4 is WRONG!
Welp, that was fun. I don't really like his tone and there's a lot of other sites for practicing these kind of arbitrary problems.
 
Top Bottom