• 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

I just started Data Structures at college and this is my 3rd computer science class. One trend that I've noticed with computer science teachers is that they don't respect my time :| they give so much god damn homework as if their class is the only thing i have to do in my life. 40 pages of small printed single spaced texted of reading and then do 6 questions 2 of them being full programs. Like cmon man, I have another class and a job too.
 
I just started Data Structures at college and this is my 3rd computer science class. One trend that I've noticed with computer science teachers is that they don't respect my time :| they give so much god damn homework as if their class is the only thing i have to do in my life. 40 pages of small printed single spaced texted of reading and then do 6 questions 2 of them being full programs. Like cmon man, I have another class and a job too.

Don't take this the wrong way, honestly, but...

Welcome to college. If you want less work you can try a community college or an online university, which are more friendly towards people who work part time. If you're going to a university, you should expect a continually increasing workload over the 4-6 years you're there. And that's the way it should be. You're there to get a college education, the professors reducing the workload because of students who work part time jobs is unfair to the students who are there to focus on their education.

It's not that they're not respecting your time, it's that you're not respecting the reason you're there in the first place. I know it's tough, with cicrumstances and all, job, bills, etc, but unfortunately it's not the school's problem. You can also reduce your course load if you need to.
 
Don't take this the wrong way, honestly, but...

Welcome to college. If you want less work you can try a community college or an online university, which are more friendly towards people who work part time. If you're going to a university, you should expect a continually increasing workload over the 4-6 years you're there. And that's the way it should be. You're there to get a college education, the professors reducing the workload because of students who work part time jobs is unfair to the students who are there to focus on their education.

It's not that they're not respecting your time, it's that you're not respecting the reason you're there in the first place.

lol why you just shitted on me though. Nah bro I can take it, i've done it just fine the other 2 classes, all I'm saying is that it would be a nice surprise if just one week they went easy with the homework.
 
lol why you just shitted on me though. Nah bro I can take it, i've done it just fine the other 2 classes, all I'm saying is that it would be a nice surprise if just one week they went easy with the homework.

Try to optimize your schedules so you get like 1 hard class, 1 medium class, and 1 easy class each semester. And I don't mean an easy teacher for an otherwise hard class, because that's doing yourself a disservice in that you're missing out on a lot of stuff you could have learned. But if there's a class that you know is going to be a lot of work, like Data Structures, choose one of your core curriculum classes and maybe something like Discrete Math for your others.

Maybe you're already doing this though, idk.

Sorry if I came off rude, I just remember being back in college and everyone constantly bitching about how the professors were jerks, unfair, gave too much work, graded too harshly, etc. It's like dude welcome to being an adult. I've seen it so much now that I'm bitter about that kind of stuff, own up to your responsibility and handle it :-/ (not you, just saying in general)
 

squidyj

Member
I'm having a hard time understanding the behavior of c++ in a particular instance.

Code:
    //This type provides the accessor functions that unify swizzle and vector access
    //using array syntax at runtime
    //this makes it easy to implement free functions that iterate over the elements of a given vector.
    template<typename T, size_t N, size_t... remainder>
    struct Swizzle
    {
        static constexpr size_t indices[N] = { remainder... };
        T& operator[] (int index)
        {
            //cast to base data type, increment by value at index, then dereference
            return *((T*)this + indices[index]);
        }

        T operator[] (int index) const
        {
            //cast to base datatype, increment, then dereference
            return *((T*)this + indices[index]);
        }
    };

    //namespace scope declaration of our index arrays
    template<typename T, size_t N, size_t... remainder>
    constexpr size_t Swizzle<T,N,remainder...>::indices[];

    template<typename T, size_t N>
    struct Swizzle<T, N>
    {
        T& operator[] (int index)
        {
            return *((T*)this + index);
        }

        T operator[] (int index) const
        {
            return *((T*)this + index);
        }
    };

I have swizzles with their ordering encoded in their type and then a specialization of the swizzle template that specifies no ordering that uses a different array operator and doesn't require the array of indices.

Code:
    template<typename T, size_t N, size_t... rem1, size_t... rem2>
    void myFunction(Swizzle<T,N,rem1...> &lhs, Swizzle<T,N,rem2...> &rhs)
    {
        Vector<T,N> out;
        cout << lhs << '\n' << rhs << '\n';
        for(size_t i = 0; i < N; i++)
        {
            out[i] = lhs[i] + rhs[i];
        }
        cout << out;
    }

This function is simply an example of an unoptimized operator. it takes two vectors, each of which may or may not have an ordering and adds them together. It works when I pass by reference and fails miserably when I pass by value. walking through the code step by step at execution it seems to be executing the correct code path in both cases, it calls the correct version of the array operator. I'm not clear on what exactly is causing the failure here.
 
I'm having a hard time understanding the behavior of c++ in a particular instance.

Code:
    //This type provides the accessor functions that unify swizzle and vector access
    //using array syntax at runtime
    //this makes it easy to implement free functions that iterate over the elements of a given vector.
    template<typename T, size_t N, size_t... remainder>
    struct Swizzle
    {
        static constexpr size_t indices[N] = { remainder... };
        T& operator[] (int index)
        {
            //cast to base data type, increment by value at index, then dereference
            return *((T*)this + indices[index]);
        }

        T operator[] (int index) const
        {
            //cast to base datatype, increment, then dereference
            return *((T*)this + indices[index]);
        }
    };

    //namespace scope declaration of our index arrays
    template<typename T, size_t N, size_t... remainder>
    constexpr size_t Swizzle<T,N,remainder...>::indices[];

    template<typename T, size_t N>
    struct Swizzle<T, N>
    {
        T& operator[] (int index)
        {
            return *((T*)this + index);
        }

        T operator[] (int index) const
        {
            return *((T*)this + index);
        }
    };

I have swizzles with their ordering encoded in their type and then a specialization of the swizzle template that specifies no ordering that uses a different array operator and doesn't require the array of indices.

Code:
    template<typename T, size_t N, size_t... rem1, size_t... rem2>
    void myFunction(Swizzle<T,N,rem1...> &lhs, Swizzle<T,N,rem2...> &rhs)
    {
        Vector<T,N> out;
        cout << lhs << '\n' << rhs << '\n';
        for(size_t i = 0; i < N; i++)
        {
            out[i] = lhs[i] + rhs[i];
        }
        cout << out;
    }

This function is simply an example of an unoptimized operator. it takes two vectors, each of which may or may not have an ordering and adds them together. It works when I pass by reference and fails miserably when I pass by value. walking through the code step by step at execution it seems to be executing the correct code path in both cases, it calls the correct version of the array operator. I'm not clear on what exactly is causing the failure here.

Passing by value creates a new instance of the Swizzle class. The index operator then references itself via the this pointer, which is going to point off into junk
 

squidyj

Member
Passing by value creates a new instance of the Swizzle class. The index operator then references itself via the this pointer, which is going to point off into junk

Okay so even though my vector is of type Vector which inherits from Swizzle, it invokes the Swizzle copy which fails to copy the data present only in the derived type?
 
Okay so even though my vector is of type Vector which inherits from Swizzle, it invokes the Swizzle copy which fails to copy the data present only in the derived type?

I actually didn't even notice that Vector inherited from swizzle since the code for Vector wasn't posted. But yea, what you described is exactly right. That behavior even has a name because it's such a common gotcha. It's called slicing, you can google that to find a bunch of explanations. But the short version is that not only does it make a copy of the data in the base class, but that it only copies the base class. So any members that are declared in the derived class are not part of the copy, and if the base class references them (which it seems you do by way of casting this to a T*), it will be undefined behavior.

All that said, I'm still a little confused what you're trying to accomplish with this code. Looking at Swizzle and this horrible reinterpret_cast I just cringe a little. Ignoring all the template machinery you've created here, what's the end goal? What's your vision of the final line of code you'd like to write that does all kinds of weird magic in the background?
 

RustyO

Member
With the caveat of asking a stupid question... I wanted get some comments / thoughts / advice about merging C# and C++; or porting C# code over to C++

I've developed a C# WinForms program, and as it turns out, a bunch of users want to, or already do use it on OSX via Wine. For various other / future projects, I'm interested in learning C++ and the Juce library.

At present there is only two main issues with the OSX/Wine scenario:

a) Graphics: Because it seems Wine doesn't handle drawing (Some drawings come out blocky) and transparency (e.g. a transparent label doesn't seem to work at all)
b) Native OSX: As some people want that, rather then being forced to use Wine.

Obviously I can tinker a bit in C#, but my C++ is extremely low / non existent, and I'm under no illusions that it would be a fairly hefty sized job, for little benefit given the above, which I should be able to work around, but given more long term plans, that is perfectly fine.

However, in some ways I feel it would be a good excerise, as I would be working off a known base / my existing code. Flipside there is there is a lot of gui elements, all customised controls, fairly convulted/heirachal classes, lots of xml, and so forth.

So I would basically be recreating the UI/UX from sratch. I've been looking at creating C# dlls to call from C++, but that seems like maybe more hassle then its worth?

So I'm trying to weigh up what the various options available are, and what would be the best plan overall. And given that this doesn't *need* to be done, but would be a nice to have to leverage off C++/Juce for the GUI, cross-platform, and skill set benefits...

- C++ GUI with C# dlls? (Core engine ported over)
- Just learn C++ and rewrite from scratch?
- Not stress about it / too much hassle and learn C++ with "new" projects?
 
With the caveat of asking a stupid question... I wanted get some comments / thoughts / advice about merging C# and C++; or porting C# code over to C++

I've developed a C# WinForms program, and as it turns out, a bunch of users want to, or already do use it on OSX via Wine. For various other / future projects, I'm interested in learning C++ and the Juce library.

At present there is only two main issues with the OSX/Wine scenario:

a) Graphics: Because it seems Wine doesn't handle drawing (Some drawings come out blocky) and transparency (e.g. a transparent label doesn't seem to work at all)
b) Native OSX: As some people want that, rather then being forced to use Wine.

Obviously I can tinker a bit in C#, but my C++ is extremely low / non existent, and I'm under no illusions that it would be a fairly hefty sized job, for little benefit given the above, which I should be able to work around, but given more long term plans, that is perfectly fine.

However, in some ways I feel it would be a good excerise, as I would be working off a known base / my existing code. Flipside there is there is a lot of gui elements, all customised controls, fairly convulted/heirachal classes, lots of xml, and so forth.

So I would basically be recreating the UI/UX from sratch. I've been looking at creating C# dlls to call from C++, but that seems like maybe more hassle then its worth?

So I'm trying to weigh up what the various options available are, and what would be the best plan overall. And given that this doesn't *need* to be done, but would be a nice to have to leverage off C++/Juce for the GUI, cross-platform, and skill set benefits...

- C++ GUI with C# dlls? (Core engine ported over)
- Just learn C++ and rewrite from scratch?
- Not stress about it / too much hassle and learn C++ with "new" projects?

Have you considered porting your application to QT?
 

Somnid

Member
With the caveat of asking a stupid question... I wanted get some comments / thoughts / advice about merging C# and C++; or porting C# code over to C++

I've developed a C# WinForms program, and as it turns out, a bunch of users want to, or already do use it on OSX via Wine. For various other / future projects, I'm interested in learning C++ and the Juce library.

At present there is only two main issues with the OSX/Wine scenario:

a) Graphics: Because it seems Wine doesn't handle drawing (Some drawings come out blocky) and transparency (e.g. a transparent label doesn't seem to work at all)
b) Native OSX: As some people want that, rather then being forced to use Wine.

Obviously I can tinker a bit in C#, but my C++ is extremely low / non existent, and I'm under no illusions that it would be a fairly hefty sized job, for little benefit given the above, which I should be able to work around, but given more long term plans, that is perfectly fine.

However, in some ways I feel it would be a good excerise, as I would be working off a known base / my existing code. Flipside there is there is a lot of gui elements, all customised controls, fairly convulted/heirachal classes, lots of xml, and so forth.

So I would basically be recreating the UI/UX from sratch. I've been looking at creating C# dlls to call from C++, but that seems like maybe more hassle then its worth?

So I'm trying to weigh up what the various options available are, and what would be the best plan overall. And given that this doesn't *need* to be done, but would be a nice to have to leverage off C++/Juce for the GUI, cross-platform, and skill set benefits...

- C++ GUI with C# dlls? (Core engine ported over)
- Just learn C++ and rewrite from scratch?
- Not stress about it / too much hassle and learn C++ with "new" projects?

I wouldn't bother with C++, it's not a good cross platform solution and it buys you almost nothing. I'd either use some existing way to run or convert the app (Xamarin), or rebuild it cross platform (web).
 

squidyj

Member
I actually didn't even notice that Vector inherited from swizzle since the code for Vector wasn't posted. But yea, what you described is exactly right. That behavior even has a name because it's such a common gotcha. It's called slicing, you can google that to find a bunch of explanations. But the short version is that not only does it make a copy of the data in the base class, but that it only copies the base class. So any members that are declared in the derived class are not part of the copy, and if the base class references them (which it seems you do by way of casting this to a T*), it will be undefined behavior.

All that said, I'm still a little confused what you're trying to accomplish with this code. Looking at Swizzle and this horrible reinterpret_cast I just cringe a little. Ignoring all the template machinery you've created here, what's the end goal? What's your vision of the final line of code you'd like to write that does all kinds of weird magic in the background?

The goal is ultimately to replicate GLSL syntax when working with vectors.
Here's a look a at one vector specialization.
Code:
    //sizeof Vector<float,2> remains 8
    template<typename T>
    struct Vector<T,2> : public Swizzle<T,2>
    {
        union
        {
            T data[2];
            Swizzle<T, 1, 0> x, s, u;
            Swizzle<T, 1, 1> y, t, v;
            Swizzle<T, 2, 0, 0> xx, ss, uu;
            Swizzle<T, 2, 0, 1> xy, st, uv;
            Swizzle<T, 2, 1, 0> yx, ts, vu;
            Swizzle<T, 2, 1, 1> yy, tt, vv;
        };
    };
This gives me the ability to access all the swizzles of the vector that I have defined without additional per-vector overhead so a vector remains the size of it's components.

Furthermore it allows me to define a single set of free operators and functions that will apply over all vectors and swizzles using similar syntax to myFunction.

This means I can support swizzled vectors of the sizes I want to define swizzles for (in practice this will be vectors of size 2 3 and 4) without being unable to use the same function definitions for vectors of any length.

and it gives me the opportunity to have something like

Code:
typedef Vector<float, 2> vec2;

vec2 v = vec2(0.4f, 0.5f);
v.yx += v.ss;
 
Short thoughts from work;

Android Wear is actually a rather nice platform

The Wear app for iOS opens up the audience for these watch things, and the ability to render watch faces with OpenGL ES2 opens up a bunch of possibilities. My biggest complaint right now is that ES 3.0/3.1 features seem off limits or hard to access, even though every watch so far has shipped with an ES3 capable GPU. I used Java instead of the NDK for the most recent project, and performance was better than expected with the new Android runtime. Color me impressed.

Apple Watch is pretty dang limited.

Apps get terminated at the time, animation is limited to iterating through bitmaps with a timer. Network calls are possible, but not useful because of how overeager Watch OS is to kill apps. XML based Storyboards are the only way to render your UI. If there are hopes that the Watch will become more independent of the phone in the next few years, slay them now.

Probably going to get a Sony Smartwatch on the cheap. They're fun to play with.
 
I've developed a C# WinForms program, and as it turns out, a bunch of users want to, or already do use it on OSX via Wine. For various other / future projects, I'm interested in learning C++ and the Juce library.

If your clients want to run it on OS X, just bite the bullet and learn Objective-C. Swift only extends the Objective-C runtime, so many of the same features/problems still exist on Le Swift. And using the native OS X UI bits, you'll run into less development friction that way.

You could look into bridging the Obj-C UI with C# or a similar shared data layer. But for most things, I think a re-write will save you a lot of trouble. Or as someone else mentioned, this might be a good time to look into modern JavaScript... or dare I say, Chrome Apps (which are really a form of browser extensions).
 

JesseZao

Member
If your clients want to run it on OS X, just bite the bullet and learn Objective-C. Swift only extends the Objective-C runtime, so many of the same features/problems still exist on Le Swift. And using the native OS X UI bits, you'll run into less development friction that way.

I'm currently learning Obj-C, so that's good to hear. I wasn't sure if I should bother and just learn Swift instead.
 

Somnid

Member
I'm currently learning Obj-C, so that's good to hear. I wasn't sure if I should bother and just learn Swift instead.

Objective C will probably take the better part of a decade to kill without specific intervention by Apple but it absolutely will die and nobody else will use it. If you're breaking in I'd pick it up only on a need to know basis while the transition happens.
 

JesseZao

Member
Objective C will probably take the better part of a decade to kill without specific intervention by Apple but it absolutely will die and nobody else will use it. If you're breaking in I'd pick it up only on a need to know basis while the transition happens.

Yeah. I'm not a big fan of the language, I'm just looking to get a surface level understanding of it. I'm more interested in Android development for mobile at this point.
 

Massa

Member
Yeah. I'm not a big fan of the language, I'm just looking to get a surface level understanding of it. I'm more interested in Android development for mobile at this point.

In that case try looking at Smalltalk first, just for a couple days or so. Objective-C will make a lot more sense then.
 
Anyone here tried there hand with F#?

Long long time ago, back when it was in beta and for maybe a year after it was fresh out of beta. Really cool language to program in. I did a few practical things, but I also tried writing GUI apps and stuff just for shits and giggles, to prove it could be done.
 
Objective C will probably take the better part of a decade to kill without specific intervention by Apple but it absolutely will die and nobody else will use it. If you're breaking in I'd pick it up only on a need to know basis while the transition happens.

I've shipped a Swift app, and I can't really say that knowing Swift without Objective-C right now helps you one bit. There's too much bridging, and language side effects that come with using Swift to ship an iOS app that will leave someone without experience in Objective-C absolutely stumped.

Take how Objective-C selectors still need to be passed into some UIKit APIs like NSNotificationCenter, and private methods in Swift aren't visible as selectors to Objective-C code. Or how the base Swift object doesn't offer a hashable implementation and copy constructors like Objective-C's, making dealing with Sets and Dictionaries tricky without subclassing Objective-C's NSObject. There is also an entire laundry list of NSCoder features to support encoding objects to serialized data formats that Swift doesn't support out of the box without subclassing NSObject. Or how Swift allows you to create structs with pass-by-value semantics and classes with pass-by-reference semantics, but for a reason that takes time to think about how Objective-C's blocks work, you _cannot_ reference self within a closure created within a struct because of how all references to that struct are pass-by-value. In addition, you need protocols designed for delegate references to subclass "class" because otherwise, there is no way to make a weak reference to that delegate, because the base protocols assume that delegate object could potentially be an object that only has pass-by-value semantics.

This makes sense with some thought if you're aware of Objective-C, how the runtime works, and how ARC works. But matters like the above make Swift a poor fit for someone just getting into iOS or OS X development. In my humble opinion.

A design decision was made to make Swift interoperate with Objective-C above all else. The language really isn't better off for it.


Silly tangent: I still prefer Swift and Objective-C over Android's Java. It would be nice if Google gave us some lambdas to play with. Using another JVM language seems a bit much for modern language features like that.
 

Ashes

Banned
I got bored by Sharp. Will return to it one day. Python was cool. Did a few things but don't really have the motivation to do stuff in my free time.

Udacity is cool though. And it uses python. But the course I'm going through is structured to go at a good pace.
 

Fury Sense

Member
Anyone here used Core Data with Swift?

I'm a beginner and am getting frustrated trying to understand what I find on google and stackoverflow.

I have the simplest application. A master-detail ios app that uses core data to manage Workout entities and HeartRate entities. Every workout has many HeartRate entities in a to-many relationship.

My tableview successfully lists all workouts and passes the selected workout to my detailviewcontroller, but from there, I cannot figure out how to access the related HeartRate entities. All I want is an array of HeartRates so that I can put them in my graph.

So
1. How do I make sure my HeartRate entities are properly saving with relationship to the workout?
2. How do I get all heart rates related to my specific workout object?
3. How do I turn whatever that is into an array of floats?

I've been trying to figure this out for about 4 days straight now. I've seen so many different half-implementations online and piecing them together has been hell. I don't understand the official apple documentation either (they never have any examples and the code is all objective-c which adds another level of difficulty).

Does anyone just have some sample code or know where I should look?
 
Does anyone just have some sample code or know where I should look?

I'd recommend Tom Harrington's book, but I think Tim Roadley's book might have taken its place. There be Objective-C here, but honestly Core Data is so strongly tied to that language that some understanding of how dynamic dispatch works there and how CD's Managed Objects differ from plain old NSObjects goes a long, long way.

There are hopes among some in the community that something like C#'s LINQ will take the place of Core Data for Swift, someday. It would be nice, and it would play more to Swift's strengths.


Personally I use SQLite directly with FMDB for iOS projects when I can make architecture decisions. I've fixed one too many Core Data projects/ongoing headaches to care about that monster anymore. There's a swiftFramework branch on the main repo that works great with Swift projects.
 
Wow. Didn't know it was that bad.

Well, it's more like Rails and AngularJS in that most every startup or small, young team (in my experience) seems to have been sold on using it, then they later run into problems with it at some point. Typically with customizing it as they wish, and ongoing problems with performance as the app scales in complexity.

Still though, I like SQL. It is good. It's easier to optimize around a few good SQL queries compared to diagnosing performance problems within an ORM.
 

Ape

Banned
I have my combo boxes in my access form filtering the data in my data sheet sub form and requerying every time one is selected so that they filter in the way that slicers do.

Everything works great until I clear the slicers. My slicers show as cleared on the data sheet, but the selected filter remains selected in the combo box and the other filters are requeried based on the selected filter in the combo box.

When I clear the filters I need the combo boxes to show as blanks. I tried adding a blank row into the row source of the combo boxes, but when selected this null field requerys the other combo boxes and their field selections become null based on this. Is there any way to make the filters behave more like a slicer when clearing them?
 

Pau

Member
Hey everyone. I'm a C++ baby trying to mess around with some of the practice problems in my class by making them more complicated but I'm stuck.

The original program is just printing out the second word in a sentence. I'm trying to make a program that asks the user for a sentence, then asks the user to choose either the first, second, etc. word in the sentence, and then program will print it out. So far I've gotten it to work as long as the user doesn't ask to print out the last word in the sentence. Why is that happening? I'm assuming it's the loop causing the problem?

Code:
#include <iostream>
using namespace std;

int main() {
	//Program to print out the first, second, ... n word of a sentence.

	//Ask user for the sentence
	string sentence;
	cout << "Please enter a sentence:" << endl;
	getline(cin, sentence);

	//Sentence cannot begin with spaces.
			while(sentence[0] == ' ')
			{
				cout << "Sentence cannot begin with a space. Please try again." << endl;
				cin.clear();
				cin.ignore();
				getline(cin, sentence);
			}

	//Ask the user for n
	int n;
	cout << "Choose the word to be printed out by typing." << endl;
	cout << "(Ex: For the first word, type 1; for the second, type 2, etc.):";
	cin >> n;

	int i; //position in string
	int p = 1; //counter for loop
	string word;

	while(p <= n)
	{
		//prints out pth word character by character
		while(sentence[i] != ' ')
			{
				word = word + sentence[i];
				i++;
			}
		//moves through all spaces after pth word
		while(sentence[i] == ' ')
			{
				i++;
			}
		//If not the word user is looking for, erases word to start over

		if(p < n)
			word = "";
		p++;
	}
	cout << word;
}
 
Code:
		//prints out pth word character by character
		while(sentence[i] != ' ')
			{
				word = word + sentence[i];
				i++;
			}
Think about what happens in this loop when it's the last word. Let's assume we only have one word: 'word'. We get 'w', then 'o', then 'r', then 'd'... then what? Certainly not a space, so the loop won't quit. You loop until you find a space, regardless of whether the string has ended or not. You need to add some kind of condition so the loop doesn't go on if you've already gone through all of the string.
 

wolfmat

Confirmed Asshole
Strings are terminated with the special NUL character. In string notation, that is '\0'. You need to also check for that one where you test if the word has ended; otherwise, you will traverse the complete allocated memory if your sentence doesn't end with a space, and then attempt to traverse outside of your memory, which your memory controller detects. The operating system then traps that with a segmentation fault. This is called illegal access.
 
Strings are terminated with the special NUL character. In string notation, that is '\0'. You need to also check for that one where you test if the word has ended; otherwise, you will traverse the complete allocated memory if your sentence doesn't end with a space, and then attempt to traverse outside of your memory, which your memory controller detects. The operating system then traps that with a segmentation fault. This is called illegal access.

Pretty sure std::strings aren't null terminated. The classic C char* are, but not the more modern strings.
 

wolfmat

Confirmed Asshole
Pretty sure std::strings aren't null terminated. The classic C char* are, but not the more modern strings.

The cin >> n; operation generates a string via std::istream, which will be null-terminated (cin will treat the input as a C string); but you're right anyway, length() should've been used instead because in the general case, null-termination cannot be guaranteed. So Pau should check if i is smaller than the length of sentence instead of checking for \0.
 

Slavik81

Member
Pretty sure std::strings aren't null terminated. The classic C char* are, but not the more modern strings.
In practice, std::string instances are null-terminated to satisfy the requirements of operator[] and c_str(). Specifically:
C++11 operator docs said:
If pos == size(), a reference to the character with value CharT() (the null character) is returned.

For the first (non-const) version, the behavior is undefined if this character is modified.
c_str docs said:
The pointer is such that the range [c_str(); c_str() + size()] is valid and the values in it correspond to the values stored in the string with an additional null character after the last position.
 

Pau

Member
Thank you everyone! I had tried using length.() before to get the last position, but for some reason I kept using OR instead of AND (and why that was wrong didn't really click until Chainsawkitten's post). I had also looked up the null termination stuff, which I can't pretend to understand fully, but I assumed there was a solution based on stuff we already learned in class.

Code:
int l;
l = sentence.length() - 1;

while(sentence[i] != ' ' && i < l)
			{
				word = word + sentence[i];
				i++;
			}

if(i == l)
		{
			word = word + sentence[i];
		}
while(sentence[i] == ' ')
		{
				i++;
		}

A small question about that last if statement. Is it good umm... programming etiquette to leave it without an else expression? I could also do the following, does that make the program more efficient or is it negligible?

Code:
		if(i == l)
		{
			word = word + sentence[i];
		}
		else
		{
			while(sentence[i] == ' ')
				{
					i++;
				}
		}
 

Makai

Member
Starting to learn Haskell with no functional programming experience and I can already tell this is going to be a mind-bender.
 

Makai

Member
A small question about that last if statement. Is it good umm... programming etiquette to leave it without an else expression? I could also do the following, does that make the program more efficient or is it negligible?
This is just an aside, but I would recommend not using lowercase L as a variable name. It looks just like the number 1 in a lot of fonts. I was confused for a little bit.
 

Makai

Member
Anyone here tried there hand with F#?
My coworker used F# for making a data-driven Unity application. Kinda neat since it's not officially supported by Unity but it works because F# and C# use the same IL. Pattern matching and pipe operator were the main features he mentioned. I'll probably supplement my own C# with F# eventually.
 

Droplet

Member
Thank you everyone! I had tried using length.() before to get the last position, but for some reason I kept using OR instead of AND (and why that was wrong didn't really click until Chainsawkitten's post). I had also looked up the null termination stuff, which I can't pretend to understand fully, but I assumed there was a solution based on stuff we already learned in class.

A small question about that last if statement. Is it good umm... programming etiquette to leave it without an else expression? I could also do the following, does that make the program more efficient or is it negligible?

There is no etiquette on using if/else statements. It's entirely context based. In your case, uh...well, I'm not really sure what your program is doing, but it seems like sentence == l should be your termination point, so I don't know why you would have code afterwards. I want to say it would be better to have the else there, but I think you could more efficiently stick all of this into the first while statement.

Just generally speaking, if/else statements are used if you want something to apply separately to different cases. For example:

Code:
int evens = 0, odds = 0;
int i = 1;
while (i <= 100) {
  if (i%2 == 0) {  //is i divisible by 2?  if yes then add to evens
    evens++;
  }
  else {
    odds++;  //i isn't divisible by 2, add to odds
  }
  i++;
}

An example where you might want to use just an if:

Code:
int evens = 0, numbers = 0;
int i = 1;
while (i <= 100) {
  if (i%2 == 0) {  //is i divisible by 2?  if yes then add to evens
    evens++;
  }
  numbers++;  //doesn't matter if i is divisible by 2, just add it to numbers
  i++;
}


I also agree with Makai here, l is very close to a capital i or a 1, and you should also name your variables to actually describe what they are. In this case, it's length of the sentence, so something like sentence_length might be a good choice (I forget what the naming conventions of C++ are, maybe it's sentenceLength).

edit: I hope I didn't fuck that up, I'm tired and the damn thing submitted before I finished :(

edit50: LOL oops ok so I might be a bit rusty on my C++. I should have just used pseudocode.
edit51: actually, that was probably a bit complicated for what I was trying to present. Fixed again.
 
A small question about that last if statement. Is it good umm... programming etiquette to leave it without an else expression? I could also do the following, does that make the program more efficient or is it negligible?

You don't have to pair an else with an if. There are situations where you want to do something special for a certain condition, or if you there's nothing you want to do if you fail the condition.
 

tokkun

Member
Just stop using ifs altogether

Code:
while (i < 100) {
  evens += (i + 1) % 2;
  odds += i % 2;
  ...
}

Just kidding, don't do that.
 

Pau

Member
This is just an aside, but I would recommend not using lowercase L as a variable name. It looks just like the number 1 in a lot of fonts. I was confused for a little bit.
Noted! Thank you.

There is no etiquette on using if/else statements. It's entirely context based. In your case, uh...well, I'm not really sure what your program is doing, but it seems like sentence == l should be your termination point, so I don't know why you would have code afterwards. I want to say it would be better to have the else there, but I think you could more efficiently stick all of this into the first while statement.

Okay, was just checking. Thanks. :)

And the code was part of the program I posted earlier. I should have mentioned that. D:
 
I'm still in awe of the IF programming language Inform 7. Amazing that the code itself reads so much like what it produces.

Code:
In Icefinger Ford are four goblins, a bundle of kindling and a cracked cooking pot. 
The kindling is wood. The pot is clay. Instead of burning the kindling, say "The kindling is 
hopelessly too damp to catch light, even if you had something to light it with. Goblins 
[italic type]have[roman type] discovered fire, but they do keep forgetting the essential 
points." Effect of casting mend at the cooking pot: record outcome "but the pot isn't 
broken, as such: it was just badly made in the first place"; rule succeeds.
 

mltplkxr

Member
I'm still in awe of the IF programming language Inform 7. Amazing that the code itself reads so much like what it produces.

Code:
In Icefinger Ford are four goblins, a bundle of kindling and a cracked cooking pot. 
The kindling is wood. The pot is clay. Instead of burning the kindling, say "The kindling is 
hopelessly too damp to catch light, even if you had something to light it with. Goblins 
[italic type]have[roman type] discovered fire, but they do keep forgetting the essential 
points." Effect of casting mend at the cooking pot: record outcome "but the pot isn't 
broken, as such: it was just badly made in the first place"; rule succeeds.


That's cool. I was wondering recently if there's something that does the reverse; a parser that reads code and converts it to readable text.
 

wolfmat

Confirmed Asshole
That's cool. I was wondering recently if there's something that does the reverse; a parser that reads code and converts it to readable text.

On a theoretical level, any programming language that is Turing-complete can be the target language of an abstract reverse-engineering operation that takes machine instructions and produces code in said language; so as soon as you have a Turing-complete language that generates machine instructions via code that is readable text, you can
1) Take program code in some other language, compile it
2) Decompile it to the readable-text code

Examples for languages that feature code in readable text: SPL, ArnoldC, Chef, LOLCODE.
Not sure if those match EXACTLY what you had in mind. But imagining a more boring language that just verbosely explains operations is not hard. So there you are -- it's possible.

Not sure if decompilation is baked into any tool that compiles from these languages. So it's maybe not readily available.
 

Makai

Member
Has anyone worked on a large application using functional programming? I am learning Haskell now after using C# for a few years. It seems like FP solves all of the problems of OO without introducing its own. Surely, there are reasons why OO is dominant.
 
Has anyone worked on a large application using functional programming? I am learning Haskell now after using C# for a few years. It seems like FP solves all of the problems of OO without introducing its own. Surely, there are reasons why OO is dominant.

Pretty sure a lot of people find OO easier. I never got to use functional programming in any projects, so my experience is very basic.
What's your opinion on what kind of problems FP solves? I'd love to hear! :)
 

injurai

Banned
Has anyone worked on a large application using functional programming? I am learning Haskell now after using C# for a few years. It seems like FP solves all of the problems of OO without introducing its own. Surely, there are reasons why OO is dominant.

I too am learning haskell. I've been on a bit of a language hop for a while now. In part because I found myself disliking OO. I recently read about haskell being used at Facebook to implement a parallelized spam filter. OCaml get's some decent mileage as it's not pure functional, haskell is really the only one of that kind.

I know one major advantage of functional programming is the ability to more easily rationalize about complexity. At Least the statically typed ml-like languages. But it seems much harder for people to implement all the little details. OO is easier to encapsulate some component then throw it up into a system of components. You get to think about the world as objects, not as some mathematical structure that represents some lambda calculation.

A lot of the functional languages have been half-baked the past decade, or stuck as academic languages. You have to remember that C success is directly related to Unix being popular. Java was pushed big time through marketing and sales to corporations. Universities basically pumped out generations of programmers who were initially inclined to certain flavors. There has yet to be functional language that really rises up to own a domain.

But that's just what I've gathered from my increasing interest in this area. I'm sure there is a lot more insight to be had. It can be hard though with evangelists and naysayers left and right... :|
 

tokkun

Member
Problems of functional languages?

- Functional languages do not map very directly to microprocessor architectures (outside of a few experimental dataflow processors). It's difficult for a programmer to reason about low level performance, memory, and power issues. You need a concept of state to interact with hardware.

- A lot of people have a hard time reasoning about some fairly central functional programming elements like recursion and folding. They don't conceptualize the universe that way. People like OO languages because most people conceptualize the universe as a collection of objects interacting with each other in their everyday life.

- Most of the modern languages are hybridized anyway. You can have persistent state in Scala, anonymous and first-class functions in C++, etc. So I think it comes down to whether a functional language really offers that much more than the functional programming features of imperative languages, considering the support that imperative languages have in terms of existing toolchain, libraries, knowledge base, and so forth.
 
Top Bottom