Basic Concepts of Programming

Started by
18 comments, last by ChaosEngine 10 years, 9 months ago

I'm hearing a lot of fancy words the more I grow interested in programming. I don't really understand a lot of it. I wish programming tutorials would give more information about what they're talking about. Let's use C++ for example.

I know that setting a function to void means that it doesn't return a value. Returning 0 simply means that the program ran correctly. No programming tutorial has told me more than this. They have only ever elaborated on those facts. When I ask myself "In what situations should I set a function to void?" or "If I return 0 in another function, what would happen? Why would it cause an error?" I don't know how to answer them.

These might seem like insignificant details to you, because I could go on without them. But I want to know exactly when I should be using void, and when I should be returning a variable.

Object Oriented Programming is said to take data and code and put them into an object. They say this differs from traditional programming methods but I have no idea what traditional methods were and how different they were. I don't know the difference between my "code" and the "data". Can anyone please relate to me and see why I'm struggling?
It's almost like nobody bothers to sit down and take the time to explain why these things are so. Every tutorial I watch, book I read does not elaborate enough and it drives me up the wall. But enough complaining.

Can anyone give me some basic run through of the most basic principles of coding. I understand what integers are, floats, strings, booleans - for example. I know that it's more effective to use a single instead of a double when you're working with a smaller number, but why? I just need some explanations on common misconceptions and reasoning behind the crap I'm typing. I see it coming together, I see it working, but I don't know why it's working and I struggle to replicate it later because I don't know the reasons why I put certain things in places the first time.

If typing something up here is too much to ask for, that's probably right, lol. I'll appreciate any information or tutorials, videos etc. that anyone can link me to in terms of coding and their core foundations and reasoning behind its basic principles. Just the silly things that nobody bothers to elaborate on as I explained above.

Advertisement


Can anyone please relate to me and see why I'm struggling?

I can't really. I mean I never really encountered these problems, but let me see if I can explain my understanding.

1. Computers are "computation machines". Thus all of the things they do boil down to math. Do you know what a function is? Do you know how to generate functions to solve word problems? Do you know how to combine functions to achieve more complex results? That is all programming is, and all computers do when you boil it down.

2. All these things are tools you use to solve problems. Why would you return void? Because your problem doesn't require a result. Many things are like this. The tutorial can't say when you would use them because they don't know the problems you face.

Now on to the specifics:


"If I return 0 in another function, what would happen? Why would it cause an error?"

If you return 0 in another function, the caller would get 0 as a result. It would only be an error if you were really supposed to get 1 or 42 or whatever as a result. And even then your program would run, just incorrectly.


They say this differs from traditional programming methods but I have no idea what traditional methods were and how different they were.

Traditionally, programs were very function oriented. They said "do this, then do that, if x=y then this other thing". Object oriented programs are designed more like "make a dog and a cat. make the dog chase the cat". Instead of focusing on the operations/recipe to do something, it focuses on modeling the parts of the problem as objects.


I don't know the difference between my "code" and the "data".

Data is variables.

Code is operations performed on variables.


I know that it's more effective to use a single instead of a double when you're working with a smaller number, but why?

That's the thing, it isn't always true. singles are 4 bytes (in most languages) doubles are 8 bytes (in most languages). So if you don't need the range (larger min/max values) or precision (more decimal point accuracy) of a double then you can use 4 less bytes to store that variable. Since you have less bytes to work with, operations should be faster too.

Unfortunately, on some machines, working with 8 bytes at a time "fits" better with how the processor works, so is actually faster.

That said, the performance difference is negligible and saving 4 bytes here and there is also usually meaningless these days.

If you're able to, attend some intro to programming classes -- good ones will cover a lot of what you seem to be interested in. If that's not possible or you want to get started before you're able to do that perhaps try Stanford's "Introduction to Computer Science: Programming Methodology" and MIT's "Introduction to Computer Science and Programming", both of which provide most (if not all) course materials including video lectures and notes for free online.

It might also be beneficial at some point to learn the basics of an assembly language -- it's very low level, and will give you a bit more of an idea of how the computer actually functions, as you're more directly interacting with the device.

Unless you're really just in this out of interest and don't care at all about productivity, try not to get caught up on wanting to know all of these details. It's good to learn the basics and to understand how things work, and I think everyone should learn at least the basics of how things work at a lower level at some point, but you could go on forever learning how things work at progressively lower levels until you end up studying physics rather than computer science and can still only output basic text to a console window.

Hope that helps! smile.png

- Jason Astle-Adams

as stated above, "data" is all the variables in your program. most typically, you'll be dealing with ints, floats, arrays of chars (null terminated strings), and structs.

"code" is the machine instructions that operate on the data.

your code:

a=a+b;

gets translated to machine code by the compiler that:

1. copies the value at the memory address of variable "a" to a register in the CPU.

2. copies the value at the memory address of variable "b" to a second register in the CPU.

3. adds the second register to the first register (adds b to a).

4. copies the first register to the memory address of variable "a".

"traditional" and "OO" programming are two different ways of organizing the code and data in your source code.

in traditional programming, you have variables (data), and you have functions (code). scope (what variables a function can access) is controlled by where the declaration of global varibles appear in a module (a source code file), by declaring variables locally to a function (accessible only by that function) , and by declaring global variables as extern in a header file (externally accessible by functions in other modules). any function can use any variable within scope. while this is powerful, and handy when operating on two different types of data at once, it can also lead to lots of inter-dependencies in the code, which makes it easy to break when modifying.

OO takes the variables and functions for an "object" and lumps them together. there's tighter control on what functions (methods in OO speak) can access a given variable (an objects variables are only accessed by that object's methods). this makes the interface of an object pretty clean and easy to work with. and you can mod an object's methods and variables without breaking anything as long as the object's API doesn't change.

Note that you can do both. before C++ and OO came along,there were ADT's - abstract data types. the "grandfather" of OO, you might say. an ADT is defined as a collection of related variables, and the functions that operate on them. sounds suspiciously like the basic definition of an object eh? in traditional ADT implementtion, and ADT (an object) is implemented in its own module ( source code file). the variables are global to the module. the "public" functions are declared extern in the header file. this gives you OO without polymorphism and inheritance.

you can also declare variables in an ADT as extern and write fuctions that use more that one ADT at a time (like a method that operates on two different types of object's variables directly). this avoids the slowdown of going thru APIs for get and set variable methods and such by accessing variables directly. however, this does add inter-dependencies to the code. if you change the ADT's data structure, you break the code. so your direct access code becomes dependent on the data structures and must be modded whenever they are. its these types of inter-dependencies that OO is designed to avoid.

========================================================

an example of a void function in traditional programming:

void print_it()

{

printf("hey there world! what's up?\n");

}

void main()

{

int a;

for (a=0; a<10; a++) print_it();

}

print_it doesn't need to return a value so its return type is void.

========================

an example of a function that returns a value in traditional programming:

int is_pos(int a) // returns 1 if a>0, else returns 0.

{

if (a>0) return(1);

return(0);

}

void main

{

int b;

b=5;

if (is_pos(b)) printf("Its postive!\n");

else printf("not postive!\n");

}

is_pos needs to return an int (0 or 1), so its return type is int.

return values are used when you want a function to return a (simple) result. if you don't need to return a result, you use "void" to indicate this in the C/C++ language.

Norm Barrows

Rockland Software Productions

"Building PC games since 1989"

rocklandsoftware.net

PLAY CAVEMAN NOW!

http://rocklandsoftware.net/beta.php

I hear ya. I'm definitely the type who needs to understand things to their very core before I'm satisfied. One of the best ways to learn this stuff is to program on a system like Gameboy Advance, where there is no operating system and you get to interact with the hardware directly. Then you really get to understand how computers work. Writing in assembly language helps too.

Code and data are really the same thing... just bits in memory. But they're usually kept in separate areas of memory, because code is generally only executed and not read and modified by the program... and data is generally read and modified by the program, but not executed.

The convention of main() returning 0 to indicate success is just that... a convention, agreed upon by all programmers, and built into compilers and operating systems, that if a program returns 0, all is well, and if not, then something went wrong. It didn't have to be 0. That's just what everyone agreed on, and is so widespread now that there's no reason to try to change it. Every other function can do whatever the heck you want... at least until you need to interact with the operating system again, and then you have to follow whatever conventions it has set up.

On a system like GBA, you can really do whatever the heck you want. The first 4 bytes of the ROM file (what goes onto the cartridge) is where the CPU starts executing from, and whatever instruction code you put there is what happens. Compilers may still force you to follow the convention of main() returning 0, but it really doesn't mean anything on a device without an operating system. However, GBA hobbyists have set things up well enough now that you just write a main function and there's already stuff in place to initialize memory and then jump to main (crt0 is the standard name for the setup stuff). But you can still write your own crt0 if you want.

To learn the reasoning behind object-oriented programming, try to write a decent sized game in C without using structs biggrin.png You'll probably end up inventing OO yourself.

this is the 2nd thread in a day you open like this.. you are doing it wrong :)

You won't learn programming in one day.. relax, take your time. Sometimes you need to be less stubborn and just accept that you are not ready to understand EVERYTHING yet and move on with your learning. In time, things will all "click" into place, or maybe they won't.. we are all different. But one thing is for sure, you won't get it in one day. It's a circular process.. you read a book and you might get 40% of it.. do some coding, read the book again, and get 50%.. do some coding and so on.

The very questions you are asking make no sense, what does it mean that you want to know exactly when you want to return void and when you want to return the value? How can we know? You're the programmer.. if you have a function that is "doing" something (ie. print a value, render a sprite) then maybe you don't return anything, if you have a function that is calculating something, then maybe you return the result of your computation.. there isn't much to explain, it will be basic basic logic and very obvious once you start programming yourself... it's impossible to understand if you dont start coding.

About tutorials.. the idea of an internet tutorial is to show you AS QUICKLY AS POSSIBLE how to do something.. it's not to explain every philosophical side of every single keyword the history that brought us here... if the tutorial author had that intention then he would have written a book, not a tutorial. If you have a decent book, you'll find all the answer there, it's just that you are not yet ready to find them.

Your thread are a clear symptom that you are overwhelmed by all this.. I think asking such broad questions, pretty impossible to answer, will just lead to a series of answer completely unrelated (lots of people shooting as many technical bla bla they know) and will just confuse you even more.. it's very common in internet forums.

again.. take your time, some things can only be understood once you have actually coded something.

Stefano Casillo
TWITTER: [twitter]KunosStefano[/twitter]
AssettoCorsa - netKar PRO - Kunos Simulazioni

First, you may be interested in this book.

But I want to know exactly when I should be using void, and when I should be returning a variable.

You should take the following with a grain of salt, as I'm one of the less experienced coders here, but it sounds to me like you're getting too caught up in the idea that there's a "right" way to do everything. The only real consideration is what you need from your code. If you don't need a function to return a value, then return type void is appropriate (this type of function is often called a routine). That the possibility exists to return an integer doesn't mean that using a routine is bad. But if you can't think of a reason or design to use an integer return value, then you don't need one. There's not exactly a rule that you're violating, just a need you don't have and an approach you're not using.

Additionally, I don't think you're in the "basic concepts of programming" realm any more. This would also explain why you aren't finding the answers you want in tutorials and books. A major design approach isn't basic, and a book that tells you what a float is probably assumes that you aren't ready for that information. And there is enough contention in the design and architecture theory space that you shouldn't count on there existing a canonical, objectively "best" practice all the time.

I know that it's more effective to use a single instead of a double when you're working with a smaller number, but why?

From this line, I'd say that you don't know that a single is better suited to a small number than a double at all. You've heard it, but haven't evaluated the statement. Think about it. Google things you're unsure about, like "what exactly is a double? What is a single?". When you get stumped, which will happen from time to time, this and other communities exist so that you can ask a clear, pointed question.

If you've reached the extent of what the average programming tutorial can teach you, then you've reached the point where you will need to take a more active role in developing your knowledge and skills. As you learn more, there is less pre-packaged material (like tutorials) available to tell you what you want to know. And while research is good, experimentation is even better. If you're unsure about something, slap together a test program that will let you examine the question yourself.

Your knowledge base builds up one piece at a time. There isn't some pile of information that can be dropped onto you that will do what you're asking.

in terms of coding and their core foundations and reasoning behind its basic principles. Just the silly things that nobody bothers to elaborate on as I explained above.

Bolded section: That's the stuff careers are made of. Professional computer scientists conduct meticulous studies and write formal papers about programming theory. If you're looking for video tutorials on this sort of thing, I think you're going to be frequently disappointed.

The rest: They aren't "silly little things". They're foundational computer science, and a book on them is more likely to be a CompSci 101 textbook than anything else. The people who "bother to elaborate" on them are professors and other instructors. jbadams' post has good information about how you can get to that kind of information.

-------R.I.P.-------

Selective Quote

~Too Late - Too Soon~

Thank you to everyone, over the past 24 hours (when it hasn't been someone telling me I'm asking the 'wrong' questions) I have gained so much understanding. I spent a good hour reading everything Norman Barrows had to say and then did a lot of research on it, all this time I've had no idea that a method and a function were the same thing, except methods are more used in Java and C++ is based on functions, they work the same way with differences based around whether they are related to an object or not. I am appreciative of all the examples given and I'm referring to this thread a lot, which has helped me learn more.

A function can perform calculations and adjust variables within itself and not accept any input or return any value such as in the first example.

A function can receive information, perform calculations on this input but still not return any information as in the second example.

A function can receive information, perform calculations on this information and also send information back when it is used as in the third example.

//======================================================================================================================

float finalValue = 0.0; //Global variable, some compilers may complain that this is actually a double since the 'f' is omitted, i.e. 0.0f

//A double takes up twice as much memory space but also has more precision.

void calculateValue(void) //This function definition has two 'voids' because nothing goes in and nothing comes out, it modifies the variable directly

{

finalValue = 10.0 * 2.0;

}

void RenderLoop(void)

{

if(20.0 == finalValue) //Here, finalValue is still 0.0 as defined at the beginning, this conditional will fail, you will not be able to eat pizza.

{

eatPizza = true;

}

//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

calculateValue(); //Now when this function is called in the render loop, finalValue is modified to have a value of 20.0

//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

if(20.0 == finalValue) //Here, finalValue is now 20.0, you will finally be able to eat pizza

{

eatPizza = true;

}

}

//======================================================================================================================

//----------------------------------------------------------------------_PART_02_---------------------------------------------------------------------------------------------------

//----------------------------------------------------------------------_PART_02_---------------------------------------------------------------------------------------------------

//======================================================================================================================

float numberOfBottlesOfRootbeer = 0.0;

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

//The following function has two inputs where the previous one had void, this means we will be giving the function information necessary for its calculations

void HowMuchRootbeerToBuy(float costOfRootBeer, float amountOfMoneyAvailable)

{

//if we have $20.00, and the Root Beer costs $2.00 per bottle then numberOfBottlesOfRootbeer will be set to 10.0 when it's called in the RenderLoop() function

numberOfBottlesOfRootbeer = amountOfMoneyAvailable / costOfRootBeer;

}

//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

void RenderLoop(void)

{

//Before we call the function, the value of numberOfBottlesOfRootbeer is still 0.0.

HowMuchRootbeerToBuy(2.0, 20.0); //Here we both call the function, and input the values for its calculations

//Now that we've called the function HowMuchRootbeerToBuy, the value of numberOfBottlesOfRootbeer is 10.0.

}

//======================================================================================================================

//----------------------------------------------------------------------_PART_03_---------------------------------------------------------------------------------------------------

//----------------------------------------------------------------------_PART_03_---------------------------------------------------------------------------------------------------

//======================================================================================================================

int starTrekEpisodeSelection = 0;

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

int SelectEpisodeToWatch(int lastEpisodeWatched) //This function is set to return an integer.

{

int incrementEpisodeWatched;

incrementEpisodeWatched = lastEpisodeWatched + 1;

return incrementEpisodeWatched;

}

//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

void RenderLoop(void)

{

//before the function SelectEpisodeToWatch() is called, the value of starTrekEpisodeSelection is 0.0.

starTrekEpisodeSelection = SelectEpisodeToWatch(15); //here the return value of the called function is being assigned to starTrekEpisodeSelection

//now starTrekEpisodeSelection integer has a value of 16.

}

Consider it pure joy, my brothers and sisters, whenever you face trials of many kinds, 3 because you know that the testing of your faith produces perseverance. 4 Let perseverance finish its work so that you may be mature and complete, not lacking anything.

sounds like you want to know whats going on under the hood, from the ground up.

check out:

1. computer architeture. this will explain what the CPU, memory etc actually do. that part about copying values from memory to registers etc.it will also tech you the value of clock cycles, cache friendly code, etc.

2. assembly. this is the most bare bones coding to the metal programming there is. stuff like:

MOV D0 [some address] // copy the value at [some address] to register D0.

most computer science is taught by what i call "black box programming":

1. you type in what they tell you,

2. a miracle occurs (this is the black box part - no clue what the computer actually does - and they don't explain it)

3. you (hopefully) get the desired output / result.

it can be helpful to understand that "miracle" part. that way you know better when to use which method to do something.

in programming, and especially games, there's usually a half dozen ways to do anything, usually none of which is optimal for all cases. the better you understand the methods, and what they do behind the scenes, the better chance you have of selecting the best one for your situation from the get go.

when you write, compile, and run a program, this is basically what happens under the hood:

1. you type in your code

2. when you hit "make or "build", the compiler translates your code to "object code".

3. the linker takes your object code, and the object code for any libs and statically linked DLLs, and hooks them all up together to make an exe file.

4. you run your exe file

5. the operating system's loader loads your exe program into ram, and fixes up (adjusts) memory addresses, based on where the program was loaded in ram, so everything points to the right address. DLLs that are not delay loaded are loaded at this time as well, as i recall.

6. the CPUs instruction pointer (address of next code instruction to execute) is set to the entry point of your exe (the address were your first instruction is).

7. the CPU starts fetching instructions from RAM, and executing them.

8. execution continues until some sort of a "halt" or "exit" or "end program" type instruction is executed.

computer architecture will teach you all about registers, ram, fetch cycles, instruction pointers, memory caches, clock cycles, bus speeds, bus widths, port I/O, and all that other cool hardware stuff.

assembly will show you the low level programming side of how to talk to all that cool hardware stuff and make it dance for you.

but assembly is too low level to get anything done quickly. enter the high level languages, such as C++.

in a high level language, instead of a more or less one to one correspondence between source code and machine code (one line of assembly = one instruction),

one line of source code generates many lines of machine code.

a=a+b:

mov r0 a

mov r1 b

add r0 r1

mov a r0

one line of source generates 4 instructions.

check out computer architecture to get a handle on what the hardware does, and assembly to get a handle on what your compiler does for you.

then try to find C++ books that don't teach "black box programming".

it seems the trend in CS is to start by taking things on faith, and picking up the background info of what happens under the hood later as you go along - usually when something doesn't work right.

Norm Barrows

Rockland Software Productions

"Building PC games since 1989"

rocklandsoftware.net

PLAY CAVEMAN NOW!

http://rocklandsoftware.net/beta.php

This topic is closed to new replies.

Advertisement