• 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

Had a somewhat bad interview experience. I was about to take a bus, when I received an unexpected call from a company. The guy told me it was a technical interview to filtrate candidates so I thought it would be just CS concepts, there was some car noise around, but I still accepted to take it at that moment.

He started asking (simple) algorithm questions and some puzzles, and everything went well except two questions where I really struggled. He gave me a few minutes to think about the answer but I still couldn't come up with anything better (and to be honest that wasn't the best place to think, especially with no paper and pencil).

Now I fear that those questions are gonna shadow the rest of the questions that I answered with confidence. I should have had declined the interview at that time...

I've interviewed with a lot of companies and that was pretty rushed. You should have declined on having the interview on that moment, especially on a bus.
 

Tamanon

Banned
So, I'm still a complete novice to programming, and my Python class only goes up to the basics of lists(which I understand are Python's arrays) and dictionaries.

I'm trying to learn more stuff on my own through various sites and experiments, but my ultimate goal is to actually write a self-testing program for my CCNA studies, and eventually whatever I want. One of the concepts that I've been wrapping my head around is Object-oriented programming, classes/methods/objects and whatnot.

My thought is that I can create chapter/test classes and then question/answer subclasses with the question, the separate answers and the correct answers all as attributes. Then I can build methods to check and display the information. From there I can give them names such as C1Q1 and C2Q3 to separate them in my eyes.

My question relates to the concept itself. I know you can store strings and numbers in lists and can randomize a pick from there. From there are you able to use that string as a call on the instance in question or just store a list of instances? What I'm thinking is that I pick a chapter or no chapter and it spits out one or more random questions. I'm not necessarily interested in how to do it yet, just if it's possible.

And I know it would probably be better to have it interact with a database, that way making a new quiz/test is easier, but I'll work on that later on:)
 
So, I'm still a complete novice to programming, and my Python class only goes up to the basics of lists(which I understand are Python's arrays) and dictionaries.

I'm trying to learn more stuff on my own through various sites and experiments, but my ultimate goal is to actually write a self-testing program for my CCNA studies, and eventually whatever I want. One of the concepts that I've been wrapping my head around is Object-oriented programming, classes/methods/objects and whatnot.

My thought is that I can create chapter/test classes and then question/answer subclasses with the question, the separate answers and the correct answers all as attributes. Then I can build methods to check and display the information. From there I can give them names such as C1Q1 and C2Q3 to separate them in my eyes.

My question relates to the concept itself. I know you can store strings and numbers in lists and can randomize a pick from there. From there are you able to use that string as a call on the instance in question or just store a list of instances? What I'm thinking is that I pick a chapter or no chapter and it spits out one or more random questions. I'm not necessarily interested in how to do it yet, just if it's possible.

Hmm, not sure if I understand everything you want to do, but I think you want to write classes that each deal with one question and then write tests for each of the classes, making sure they work as intended? Storing the answer as part of the class is maybe not ideal, you should do that in a test class (usually if you're only testing one isolated part of a class, it's called a unit test). A unit could look like this (in pseudo-code)
Code:
class FibonacciQuestion
  // Just an example function that computes fibonacci numbers
  def calcFibonacci(n)

class FibonacciTest
  def testFibonacci() 
    FibonacciQuestion fq = new FibonacciQuestion
    int expectedResult = 5
    int actualResult = fq.calcFibonacci(5)
    assert(expectedResult == actualResult)
The key thing is the assertion in the test method, what it does is make sure that the result from the function is the expected result. Otherwise it crashes the program with something like "Assertion failed in line x". You can of course do this for a lot more outputs and edge cases, like what happens if you try calculating the n-th Fibonacci number if n < 0 or if n is really big (does it crash, does it run out of stack memory and so on)
 

Tamanon

Banned
I guess it can be a bit confusing because I don't know how to speak programming that well yet lol. Basically, I'm just writing a program that I can open, it'll ask me which chapter I want to "study" and then display a question or a number of questions if I choose and the possible answers. Simple program that I'll build on from there, I just wanted something to focus on building.

Thinking of it more, I don't need a test/chapter class to begin with. If I can randomly call instances from a list, which google seems to say I can, will just have to learn how...then I can just create question classes, with question, possible answer, and answer attributes. From there I make separate chapter lists to draw from based on my choices. Then I can just do a check of user input versus answer to determine a boolean for correct.
 

Tamanon

Banned
Code:
class chapq(object):
    def __init__(self,q,a1,a2,a3,a4,a5,a):
        self.q = q
        self.a1 = a1
        self.a2 = a2
        self.a3 = a3
        self.a4 = a4
        self.a5 = a5
        self.a = a

c1q1 = chapq("Who are you?","Al","Bob","Charlie","Donna","Galina","Al")
chaps = [c1q1]
n = chaps[0]
ans = raw_input(n.q)
if ans == n.a:
    print "Correct!"
else:
    print "Incorrect"

So, I've been messing around with this a bit, and it does seem as long as I define the instance before the list itself it's able to draw the information from it based on drawing the instance name from the list. If I do the list first, it pops out an error message. In this case, I was able to replicate a question that compares the input versus the correct answer. So this definitely gets me started down my path lol.
 
Code:
class chapq(object):
    def __init__(self,q,a1,a2,a3,a4,a5,a):
        self.q = q
        self.a1 = a1
        self.a2 = a2
        self.a3 = a3
        self.a4 = a4
        self.a5 = a5
        self.a = a

c1q1 = chapq("Who are you?","Al","Bob","Charlie","Donna","Galina","Al")
chaps = [c1q1]
n = chaps[0]
ans = raw_input(n.q)
if ans == n.a:
    print "Correct!"
else:
    print "Incorrect"

So, I've been messing around with this a bit, and it does seem as long as I define the instance before the list itself it's able to draw the information from it based on drawing the instance name from the list. If I do the list first, it pops out an error message. In this case, I was able to replicate a question that compares the input versus the correct answer. So this definitely gets me started down my path lol.
A small remark, you should get used to using more descriptive variable names, especially for classes. Class names should (per convention) start with an uppercase letter and use CamelCase. This is the Python style guide, in particular this section deals with variable naming. It's a very easy mistake to make since often you have an idea and just write it down in code, not thinking about variable names or documentation and you forget about adding it later.

In reality, t doesn't really matter as long as you're just programming for yourself, but it's good to learn how to write easily readable, well-documented code because at some point, you probably want other people to read your code as well and you want them to have an easy time understanding your code.
 

Tamanon

Banned
A small remark, you should get used to using more descriptive variable names, especially for classes. Class names should (per convention) start with an uppercase letter and use CamelCase. This is the Python style guide, in particular this section deals with variable naming. It's a very easy mistake to make since often you have an idea and just write it down in code, not thinking about variable names or documentation and you forget about adding it later.

In reality, t doesn't really matter as long as you're just programming for yourself, but it's good to learn how to write easily readable, well-documented code because at some point, you probably want other people to read your code as well and you want them to have an easy time understanding your code.

Thanks, yeah I need to get into the proper style more. I was just happy I was able to make a class, lol. I'll try and incorporate that more into my stuff and my assignments at school(my teacher doesn't seem to care as long as it's vaguely understandable.)

I also really need to work on commenting period.
 
Im trying to understand how pointers and memory allocation really works before my next assignment is given, so I have a few questions. Can you allocate memory within a for loop (in C)?

I want to rework a previous project I had using these concepts. So let's say I'm given two pointers, pointer 1 will point to an array of some data, say {a,b}, and pointer 2 points to {x,y,z}. Im also given the length of each, call them length1 and length2. If these were treated like vectors, and I multiplied them, then the dimensions would change. Lets say my new "array" is :
{ax, ay, az
bx, by, bz}

It would be pretty easy for me to allocate space for the number of rows, I would simply do this:

Code:
type *r = (double *) malloc(sizeof(type)*length1);

What I'm wondering is how I can allocate memory for all the elements in each row, or if its possible. I thought of doing this:
Code:
int i;
for(i=0;i<length1;i=i+1){
type *ele[i] = (type *) malloc(sizeof(type)*length2);
  }

But I got an error. I hope its not a syntax problem, or maybe my logic is just wrong. Regardless, I'd appreciate any help.
 

Aleph

Member
You can declare an array of pointers of your type:

Code:
type *array[ROWS];

Right now, the variable "array" holds a specific number of pointers (ROWS), but we haven't specified those pointers yet. Each one of those pointers should point to an array of COLUMNS amount of values:

Code:
int i;
for (i = 0; i < ROWS; i++)
     array[i] = malloc (sizeof(type) * COLUMNS);  //allocate memory within a loop

Edit: "matrix" would be a much more suitable name for the variable "array". Im assuming (a ,b) x (x, y, z) results in a 2-row, 3-column matrix.

Now you can access your data using the array[j] notation, where i is the row, and j is the column. Optional: check that malloc() doesn't return NULL. You can also remove the pointer cast when calling malloc() as it casts implicitly.
 

Tamanon

Banned
So I've been messing around some more, trying to name things a little bit better and work with the code itself some. I know it's still sloppy, but now I'm trying to think of how I should handle a question that has multiple answers. The two options I came up with was eliminating the correct_answer attribute altogether and instead assigning boolean flags to each answer, so then I just check which ones are True/False based on the input. I'm not worried so much about how the input looks since I'll be layering a GUI over this once I get further. The other option I though of was a subclass for multiple-choice questions, but I think that's not needed. I might have to edit this a bit if it goes all wonky.

Code:
class chapter_questions(object):
    def __init__(self,question,answer1,answer2,
                 answer3,answer4,answer5,correct_answer):
        self.question = question
        self.answer1 = answer1
        self.answer2 = answer2
        self.answer3 = answer3
        self.answer4 = answer4
        self.answer5 = answer5
        self.correct_answer = correct_answer

chapter1_question1 = chapter_questions(
    "Which of the following matches a router component with its function? ",
    "A. Flash: Permanently stores the bootstrap program",
    "B. ROM: Permanently stores the startup configuration file",
    "C. NVRAM: Permanently stores the operating system image",
    "D. RAM: Stores the routing tables and ARP cache",
    "",
    "D")

chapter1_question2 = chapter_questions(
    "Which two commands can a technician use to determine whether router serial ports have IP addresses assigned to them?",
    "A. show interfaces",
    "B. show interfaces ip brief",
    "C. show controllers all",
    "D. show ip config",
    "E. show ip interface brief",
    "AE")

choice = input('Do you want question 1 or 2?')
chapters = [chapter1_question1,chapter1_question2]
current_choice = chapters[choice - 1]
print current_choice.question
print current_choice.answer1
print current_choice.answer2
print current_choice.answer3
print current_choice.answer4
print current_choice.answer5
answer = raw_input()
if answer.upper() == current_choice.correct_answer:
    print "Correct!"
else:
    print "Incorrect, the answer is " + current_choice.correct_answer
raw_input()

Hopefully this is a bit more readable without too much explanation.

Or a third option that might be better at shrinking down the effort is converting the correct_answer field to a number, such as 10001 in the case of the second question. Then I can write a short conversion of the answers to 10000 for A, 1000 for B, 100 for C, 10 for D and 1 for E. Then just add the answers given up to match against the correct_answer attribute. Since the options are closed, it would lead to no unsavory output once I throw the code on there limiting what input is accepted.
 

hateradio

The Most Dangerous Yes Man
I'd use arrays to house my question data, eliminating the need to use "A-B-C-D-E" and a string to identify the correct answer.

Code:
class QuestionData:
    def __init__(self, question, correct, answers):
        self.question = question
        self.correct  = correct
        # you can actually do a bit of a check here, to see that
        # there are only 5 questions (answers.length < 6)
        self.answers  = answers

    def correct_answer(self):
        return self.answers[self.correct]

# Create questions
ch1 = QuestionData("Which is correct?", 0, ['This one!', 'This other one?', 'That', 'Nope']);
ch2 = QuestionData("Which is correct?", 2, ['Nope', 'Over there', 'This!', 'What?']);

print ch1.question
print ch1.correct
print ch1.answers

print ch1.correct_answer()

Additionally, you can actually create a method called show_questions, or something, which actually prints all the questions out to the screen using a for since the questions are in an array.

edit: If you want to have two correct answers, I guess you could make self.correct an array, to match multiple options.
 

Tamanon

Banned
I'd use arrays to house my question data, eliminating the need to use "A-B-C-D-E" and a string to identify the correct answer.

Code:
class QuestionData:
    def __init__(self, question, correct, answers):
        self.question = question
        self.correct  = correct
        # you can actually do a bit of a check here, to see that
        # there are only 5 questions (answers.length < 6)
        self.answers  = answers

    def correct_answer(self):
        return self.answers[self.correct]

# Create questions
ch1 = QuestionData("Which is correct?", 0, ['This one!', 'This other one?', 'That', 'Nope']);
ch2 = QuestionData("Which is correct?", 2, ['Nope', 'Over there', 'This!', 'What?']);

print ch1.question
print ch1.correct
print ch1.answers

print ch1.correct_answer()

Additionally, you can actually create a method called show_questions, or something, which actually prints all the questions out to the screen using a for since the questions are in an array.

edit: If you want to have two correct answers, I guess you'd could make self.correct an array, to match multiple options.

Good ideas there, I'll give it a shot and see how it feels. I'm mainly in the experiment stage.
 
Ok C++ programmers, I need your help once again. I'm building a binary search tree and the function that is giving me problems is the one that is adding a node to said tree. I have a pointer assigned to the "head" or root node called head. Current just so happens to be assigned to the same location as head (right now). Tail references the new pointer (node). The problem is my head node's pointers (those pointing to other nodes) are getting assigned back to itself. Code:
Code:
void list::addNode()
{
        // **DEBUG**
        std::cout << "addNode: " << head << endl << flush;
        std::cout << "aN->nL: " << head->nextL << endl << flush;

        // Determine left or right direction for node
        if( tail->data > current->data )
        {
                // Recursive node placement
                if( current->nextR != NULL )
                {
                        current = current->nextR;
                        addNode();
                }
                else
                {
                        tail->previous = current;
                        current->nextR = tail;
                }
        }
        else
        {
                // Recursive node placement
                if( current->nextL != NULL )
                {
                        current = current->nextL;
                        addNode();
                }
                else
                {
                        tail->previous = current;
                        current->nextL = tail;
                }
        }

        //**DEBUG**
        std::cout << "aNE: " << head << endl << flush;
        std::cout << "aN->nLE: " << head->nextL << endl << flush;
}
Output:
Code:
addNode: 0x603070
aN->nL: 0
aNE: 0x603070
aN->nLE: 0x603070
Thoughts?

EDIT: Solved.
 
You can declare an array of pointers of your type:

Code:
type *array[ROWS];

Right now, the variable "array" holds a specific number of pointers (ROWS), but we haven't specified those pointers yet. Each one of those pointers should point to an array of COLUMNS amount of values:

Code:
int i;
for (i = 0; i < ROWS; i++)
     array[i] = malloc (sizeof(type) * COLUMNS);  //allocate memory within a loop

Edit: "matrix" would be a much more suitable name for the variable "array". Im assuming (a ,b) x (x, y, z) results in a 2-row, 3-column matrix.

Now you can access your data using the array[j] notation, where i is the row, and j is the column. Optional: check that malloc() doesn't return NULL. You can also remove the pointer cast when calling malloc() as it casts implicitly.


This makes a lot of sense, and I didn't know I could make an array of pointers. Thank you.
 

Randdalf

Member
Im trying to understand how pointers and memory allocation really works before my next assignment is given, so I have a few questions. Can you allocate memory within a for loop (in C)?

I want to rework a previous project I had using these concepts. So let's say I'm given two pointers, pointer 1 will point to an array of some data, say {a,b}, and pointer 2 points to {x,y,z}. Im also given the length of each, call them length1 and length2. If these were treated like vectors, and I multiplied them, then the dimensions would change. Lets say my new "array" is :
{ax, ay, az
bx, by, bz}

It would be pretty easy for me to allocate space for the number of rows, I would simply do this:

Code:
type *r = (double *) malloc(sizeof(type)*length1);

What I'm wondering is how I can allocate memory for all the elements in each row, or if its possible. I thought of doing this:
Code:
int i;
for(i=0;i<length1;i=i+1){
type *ele[i] = (type *) malloc(sizeof(type)*length2);
  }

But I got an error. I hope its not a syntax problem, or maybe my logic is just wrong. Regardless, I'd appreciate any help.

Another way of organising memory for matrices/grids is to simply allocate a 1-D array of size m*n and then use row-major or column-major indexing to access data. It's generally simpler and faster to do it that way as well.
 
Another way of organising memory for matrices/grids is to simply allocate a 1-D array of size m*n and then use row-major or column-major indexing to access data. It's generally simpler and faster to do it that way as well.

I'm not sure I know what you're talking about? This could be something I have yet to learn though...
 
I'm not sure I know what you're talking about? This could be something I have yet to learn though...

You can store a two-dimensional array (or any n-dimensional array, for that matter) in a one-dimensional array if you keep track of the index in the right way. Instead of indexing the two dimensions directly, like this: arr[j], you can use arr[(i * N) + j] where N is the number of rows (or columns, depending if you're using row-major or column-major order). For ease of use, you can wrap the array access into a inline method. It takes some getting used to and in C, you need to be pretty careful that your array accesses don't go out of bounds (undefined behavior, weee) but I believe it gives you a performance benefit.
 

survivor

Banned
Quick question about indenting code. In Vim, one of the settings is to use "set expandtab" which replaces tab characters with actual spaces. What's the actual advantage of this? Wouldn't using tabs instead be better since if someone else opens the same file and they use a different tab space setting, the code will still display properly?
 

Haly

One day I realized that sadness is just another word for not enough coffee.
I believe it's because the length of a tab is inconsistent whereas if you're using a monospace typeface, every space is the same.
 

usea

Member
Quick question about indenting code. In Vim, one of the settings is to use "set expandtab" which replaces tab characters with actual spaces. What's the actual advantage of this? Wouldn't using tabs instead be better since if someone else opens the same file and they use a different tab space setting, the code will still display properly?
Tabs vs spaces is a holy war.

Tabs is right, spaces is ludicrous and insane for indenting.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
So much of the programming landscape is made up of holy wars.

The crusades and jihads of our time.
 

usea

Member
Spaces are the non ambiguous and more flexible way of indenting. Spaces all the way.
If your code is tabs, whoever is viewing the code gets to decide how deep they view the indents. The weird guy who likes 2-space indents can see 2, and the guy who likes 4 can see 4. It's flexible. You encode "1 level of indent" into the file, and the viewer gets to choose how many spaces a level is.

With spaces, you just have to live with however many spaces the author put. Completely inflexible.
 
If your code is tabs, whoever is viewing the code gets to decide how deep they view the indents. The weird guy who likes 2-space indents can see 2, and the guy who likes 4 can see 4. It's flexible. You encode "1 level of indent" into the file, and the viewer gets to choose how many spaces a level is.

With spaces, you just have to live with however many spaces the author put. Completely inflexible.

Pfft, how can others appreciate your delicate attention to indents if they can modify how they look!!1
 

TheBera

Member
Hi there!
It's probably a long shot but hey, I'm desperate right now!
Does anybody here have any experience with the Foursquare API?
I have to make a simple website/program to query their database for the location of a certain venue, given the name, but I absolutely don't know how!
I was trying with a servlet on Netbeans (using this library https://code.google.com/p/foursquare-api-java/) but it doesn't work (yes, I already have all the credentials)
I don't know which language is best in this case...

Thank you very much!
 
If your code is tabs, whoever is viewing the code gets to decide how deep they view the indents. The weird guy who likes 2-space indents can see 2, and the guy who likes 4 can see 4. It's flexible. You encode "1 level of indent" into the file, and the viewer gets to choose how many spaces a level is.

With spaces, you just have to live with however many spaces the author put. Completely inflexible.

Using spaces allows for layout tricks that usually help make you code more readable. Using space also ensures you that it looks the same on everyone's screen.

Two spaces soft tabs for life.
 

Onemic

Member
Is learning C important if you're already learning C++?

And why exactly is C++ such a widely used language compared to others like Python, specifically in the gaming industry?
 
Is learning C important if you're already learning C++?

And why exactly is C++ such a widely used language compared to others like Python, specifically in the gaming industry?

No, learning C first is not important if you want to learn modern C++. If you stick to how modern C++ should be learned, you don't need to be messing with low level facilities like arrays, pointers, etc. However, if you do end up writing programs that need those you will learn some C in the process.

As to your 2nd question, the simple answer is that C++ is fast. The more in-depth answer you'll find by googling. But it all comes to C++ giving you the flexibility to allocate memory and have your program be responsible for cleaning after itself. Python has a garbage collector, that solves the "cleaning-after-itself" problem at the expense that it might run in times when you don't want to. This causes your program to take a hit on performance. In games you want all the performance you can get, hence why C++ is so commonly used.
 

survivor

Banned
Looks like I will be sticking with spaces then. Beside not like I'm sharing my code with many people in the first place so they can deal with my indentations.
 

Chris R

Member
I prefer tabs because it's quicker to navigate with keys when I'm typing. I guess if I had a third hand or something to put the cursor exactly where I wanted it I'd be a spaces person.
 

tokkun

Member
Is learning C important if you're already learning C++?

And why exactly is C++ such a widely used language compared to others like Python, specifically in the gaming industry?

C++ is very nearly a superset of C. There are only a small number of things that are legal in C and not in C++ or behave differently in C++ than C. Therefore, if you are learning C++, you are already learning the C language plus other stuff. What you probably are not learning are C design patterns or libraries that have been superceded by features in C++ and C++-based libraries.

The only time this will matter is if you are dealing with a system that has a C compiler but not a C++ compiler. As far as modern systems go, those are typically things like microcontrollers or relatively niche embedded processors.

I would not recommend that you learn C unless you have a very specific reason for doing so. I also would not recommend learning C before C++ anymore, because I think the features in C++ tend to guide users toward better design patterns that they can reverse engineer if they need to switch to C.

Quick question about indenting code. In Vim, one of the settings is to use "set expandtab" which replaces tab characters with actual spaces. What's the actual advantage of this? Wouldn't using tabs instead be better since if someone else opens the same file and they use a different tab space setting, the code will still display properly?

Here's a practical example:

Code:
some_long_function_call_name(some_long_arg_name1,
                             some_long_arg_name2,
                             some_long_arg_name3);

You can easily ensure the arguments line up if you spaces, but not if you use tabs.
 
As to your 2nd question, the simple answer is that C++ is fast. The more in-depth answer you'll find by googling. But it all comes to C++ giving you the flexibility to allocate memory and have your program be responsible for cleaning after itself. Python has a garbage collector, that solves the "cleaning-after-itself" problem at the expense that it might run in times when you don't want to. This causes your program to take a hit on performance. In games you want all the performance you can get, hence why C++ is so commonly used.

Garbage collection wouldn't necessarily have a huge effect, it is more down to the fact that python is interpreted vs compiled for c++.
 

phoenixyz

Member
Here's a practical example:

Code:
some_long_function_call_name(some_long_arg_name1,
                             some_long_arg_name2,
                             some_long_arg_name3);

You can easily ensure the arguments line up if you spaces, but not if you use tabs.

This. Spaces are much more flexible and in monospace land you can align everything exactly how you want.
 
I'm at my wits end with this Mac. Xcode decided that it doesn't want to open ANY of my iOS xib's. Nothing I do seems to work, I've tried reinstalling, using an older version, deleting every damn thing which has xcode in it's name - nothing works. Weird thing is that I can create and view OSX xib's fine - but if I try to make a new iPad or iPhone xib I can't read it. I can't compile either.

"The document "ViewController.xib" could not be opened. Could not verify document content."

At least with Windows you get friggin error codes. WTF am I supposed to do with this shit. Could not verify document content? What does that even mean??!
 

Onemic

Member
Thanks for the answers. I guess my next question is, are the concepts of matrix's, vectors, linear algebra, and quarternions covered under discrete math, something else, or are they part of their own discipline? I'm interested in going into game programming and possibly specializing in graphics engine programming among other things and heard these concepts were key, as well as a background in discrete math. If I'm aiming for this what else would I need? And is a graphics engine programmer a good field to specialize in if I wanted to go into game programming? Would the concepts required to become adept in the field be easily translatable to other programming disciplines if that job prospect ultimately doesn't follow through?
 
Thanks for the answers. I guess my next question is, are the concepts of matrix's, vectors, linear algebra, and quarternions covered under discrete math, something else, or are they part of their own discipline? I'm interested in going into game programming and possibly specializing in graphics engine programming among other things and heard these concepts were key, as well as a background in discrete math. If I'm aiming for this what else would I need? \

Linear Algebra is what you're looking for. It covers all of those. Definitely a class or two on Linear Algebra and some calculus/differential equations, if nothing more than to understand the actual physics behind what the calculations are doing.
 
Ok, another question (still C). Let's say I want to read in only specific data from a file and store it/do something with it.

For example, if I had a file that consisted of: aaaaaaa34hhhhh62.5uuuu sssss0llllll5.8ppppp

How can only read in the integers, for example? Can I use fscanf here?

Edit: Not necessarily store them, but use them for an operation, like multiplying all integers for example.
 

diaspora

Member
Thanks to the developer cmd backhanding me, I now know to declare my variables first which one of the exercises in Learn C the Hard Way neglected to follow. -_-
 
Kinda good feeling as the longest / hardest project I have been on so far is reaching to end. It turned out to be much better in 6 months that I would have ever expected but still I am not completely happy with it. Every day there are so much I want to improve, add or rewrite but I just don't have the time. Last phase of testing, bugfixing and then it's off to the client.
 

usea

Member
But they're less flexible. By a lot. And tabs aren't ambiguous at all. There's actually zero valid arguments for spaces. Even if you go and seek out pro-space arguments, you'll find they're all bunk.

http://c2.com/cgi/wiki?TabsVersusSpaces
Space pros:
1) Consistent display across all display hardware, text viewer/editor software, and user configuration options. [ Note: except proportional fonts. -- end note ]
2) Gives author control over visual effect.
3) Tabs are not as "visible" (that is, a tab generally looks just like a bunch of spaces)
The first two aren't even positives.
1) Consistent display (except when it's not) is another way of saying inflexible.
2) Gives author control over visual effect is just a repeat of point #1. It says "the indention width is encoded into the file rather than being configurable by the viewer." It's like arguing for &nbsp; and <br> everywhere in html rather than using css.
3) this is the stupidest one. Tabs are just as visible as spaces. And tabs don't look like a bunch of spaces, a bunch of spaces looks like a tab! Come on.

http://programmers.stackexchange.co...per-indentation-character-for-everything-in-e
Most of the answers here say tabs and they give good reasons. Here are the spaces arguments:
1) A tab could be a different number of columns depending on your environment, but a space is always one column.
2) you can't see the difference between spaces and tabs, they always seem to get mixed up when moving code around, and viewing the code in another program that has tabs set to 8 columns is a nuisance.
3) [some notable people supposedly argue spaces are better]
1) same argument. This is a downside; not a good thing. A tab is always one level of indent. It actually solves the whole friggin problem.
2) Because some people get the two mixed up isn't an argument for choosing A over B, it's an argument for choosing at all. The con that a tab looks like 8 spaces in terrible editors is a reason not to use terrible editors. The only ones that do this are like, nano in linux. Come on.
3) Not an argument.

Tab does the job -exactly- right. It indents code at one level per tab. Using spaces to try and mimic a tab, except taking away the customizability of the viewer, taking up more bytes in the file, making it more difficult to navigate with the keyboard, and being error-prone are all downsides. There's no upside.

There is zero reason to use spaces over tabs. Zero.
 

tokkun

Member
The "more flexible" argument would be fine if that's all it was.

The problem is that in reality what happens is that unless everyone configures their tabs to be identical, then alignment doesn't work any time you're trying to align relative to any position other than the start of the line. Then code looks different on everyone's screens.

"uniform" and "flexible" are both good things. However when you start to work on large projects with lots of collaborators, uniformity will almost always trump flexibility. That's why company style guides exist - and many of them impose rules that are a lot more restrictive than not being able to resize your indentation.
 

usea

Member
The "more flexible" argument would be fine if that's all it was.

The problem is that in reality what happens is that unless everyone configures their tabs to be identical, then alignment doesn't work any time you're trying to align relative to any position other than the start of the line. Then code looks different on everyone's screens.

"uniform" and "flexible" are both good things. However when you start to work on large projects with lots of collaborators, uniformity will almost always trump flexibility. That's why company style guides exist - and many of them impose rules that are a lot more restrictive than not being able to resize your indentation.
Resizing your indentation does not affect anybody else. It's exactly why tabs are tailor-made for projects with lots of people.

Indenting means up to the first character of the line. You use tabs to indent, and that has zero affect on aligning. If I view my indents as 8 characters wide, and you view them as 2, it doesn't change the number spaces we use to align text the same way. My alignments will look exactly correct to you, and yours will look exactly correct to me.

Here are 3 screenshots from a fairly normal editor, notepad++. You can do the same thing with basically any editor out there. It's not an advanced feature. I turned on display of tabs and spaces for demonstration. A tab is shown as an arrow, a space is shown as a dot. The text in these 3 screenshots is exactly the same. It uses tabs to indent lines, and spaces to align text. The text is aligned exactly the same no matter how wide you view your tabs (2, 4 or 8 characters wide):
NASRHAH.png

MuLvVWI.png

ll0PsWA.png

Code:
pub fn foo(x: int) {
	let r = match x {
		1 => "one",
		10 => "ten",
		_ => "not one or ten"
	};
	println(r);
}

pub fn roundedRectangleRGBA(dst: *SDL_Surface, x1: int16_t, y1: int16_t,
                            x2: int16_t, y2: int16_t, rad: int16_t,
                            r: uint8_t, g: uint8_t, b: uint8_t, a: uint8_t)
                            -> c_int {
	foo(10);
	println("sent 10 to foo");
	unsafe {
		SDL_roundedRectangleRGBA(dst, x1, y1, x2, y2, rad, r, g, b, a);
	}
}

Indenting the entire second function an extra level (the spaces having a tab before them) will not change anything. Indenting and aligning are two separate things and they don't affect each other.
 

Omikron

Member
Tabs all the way, especially when working in a team who likely have different display preferences. I like 4 spaces, another in our team likes 2 for whatever reason. If you use spaces you constantly need to refactor.
 
Tabs all the way, especially when working in a team who likely have different display preferences. I like 4 spaces, another in our team likes 2 for whatever reason. If you use spaces you constantly need to refactor.

Or, you know, adhere to a standard.
 
Top Bottom