ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
There has been great advice so far. Just wanted to add a few things.
Before you start questioning your ability to learn C, it would be worth it to yourself to question the material you're using and possibly looking around for other sources. I'm not saying the one you're using is not good but not everybody responds the same way to the same material.
Self-study is hard. You don't have an instructor that you can ask questions, or that can explain things a little better or just different if you're having trouble or rewording something that they have said. This is why it's important to take from different resources. Often times a rewording by a different author or a more elaborate explanation will make all the difference. You also don't have classmates to compare your progress with. So when you don't understand a concept you can end up defaulting to something like "I'm not smart enough", when possibly a lot of people had problems when first learning it.
In the book I learned C from the chapter on Functions is 40ish pages. There are 17 program examples to work thorough while following along and there are 15 exercises at the end. Your tutorial, combining the sections on Functions and Scope, by comparision seems quite minimal (at least I think so). Not to say the information isn't sound but personally when learning a new topic, etc, I prefer the material to be verbose and lengthy. For a reference I like terse. There isn't many examples to illustrate the concepts being taught and there are no exercises where you are to use these concepts to solve a problem (none that I saw, anyway). Both examples and exercises are paramount to having a good understanding of new material.
So, in essence, don't be so hard on yourself. Maybe try a different resource? One with exercises, etc.
Thanks for linking the tutorial. I'm going to read through it at a later date and see if I can fill in some missing blanks.
Also, I don't personally use an IDE, not that that really matters. I use Vim in the terminal and gcc to compile my programs. I haven't learned to use gdb yet, but plan to some day soon. For debugging I use the method described by Andy Alt, and you can also use the preprocessor. I really like programming in i3. I will have three windows open. One for the source code, one for gcc, and one to execute my programs. You can modify the keys used to switch windows to match the navigation keys in Vim so it's very efficient.
P.S. The book I was referring to is "Programming in C" by Stephen G. Kochan.
One source you should bookmark is the GNU libc manual. It won't teach you C syntax but it will explain the use of all the functions and how they interrelate.
My absolute favorite programming book is "Sam's Teach Yourself C in 21 Days". I got mine really cheap used. It was missing the cd with code which really was a good thing, instead of just copy and paste, I had to type What I like about this book is similar to what someone mentioned above. It has a little complete program to demonstrate everything...And it's paperback
It's kind of interesting but you can get all sorts of good programming books for pretty cheap if you get them used. I think it's because a LOT of people want to learn but they quit soon after they start.
@Andy Alt I totally agree with the cout, printf, etc method of debugging. I even started to label the debug lines with //debug (/*debug*/ in C) then it's a matter of searching the source tree to remove them when your done.
You seem to be struggling with syntax as well as organization of your programming.
You may not wish to hear this, but the best way to really learn it, is to follow a far more structured approach. Therefore this will take "time", in the measure of weeks and months. Not hours.
Absolutely someone can write, or copy/paste, a simple C program, compile it, and run it successfully, within seconds. This does not mean that they have learned anything, or that they are a competent programmer.
My recommendation is for you to learn how to design code before you write code.
The C programming language allows a great deal of flexibility with how you write it. This is very powerful, and also very dangerous. Find a set of coding guidelines that is readable and use it. Here's the GNU Coding Standards for Writing C, here's the NASA C Style Guide feel free to seek out some others.
Learn about Pseudocode, and how to express the intentions of a program in a pseudo language, so as to organize your intentions.
Start slow and follow an organized approach.
Whatever that latest code you posted is, or came from, please toss it away, or file it under former learning experiences. You're absolutely to be forgiven for the state of that, you're new and exploring, however recommend you set it aside because it is not well structured code. You're having fundamental difficulties with syntax and you're trying a number of different concepts I/O and decision flow and you've used very poor organization for your tests.
We all have a directory or more containing former code that either worked or didn't and was exploration. We also all typically have an archive of former good work we did do, that we wish to retain as future examples for the next time we approach certain efforts. Suggest you start building those types of archives of your former efforts and accomplishments. Those will help you with your future endeavors.
What I'm seeing is code which belies the original course of study which you've chosen to follow.
I had to view a bit into that course to determine whether or not they actually guided you down that path. They did not from what I can see.
Once again, no big deal, however my recommendation is that you've taken yourself down a path of disorganization.
Recommend you now stop that. If you were to come to me with that code and ask me how to fix it, my two statements would be (1) a curse phrased question about what in the world you were trying to accomplish with that, and (2) a terse statement to rewrite it.
Another point to make here is that it is perfectly possible for you to get that test code working and get it doing some thing that you wanted it to do, maybe fully, maybe more, or less than you intended. And then you'd come back to me and proclaim, "Well I got it compiled and it works! (Except for one small thing, which isn't important so I'm not going to fix it...)" But what's wrong with that is the very poor structure and organization of it all.
Think about this like installing and learning Linux. It can go 100% smoothly and work the first time with zero problems. Or it can be a painstaking process. And even if your initial introductions to Linux are perfectly smooth, you know that eventually there may be some difficulties, much like anyone encounters with computers.
Meanwhile, as with the new Linux experience, the ownership of learning C is ultimately upon you. You can post all the code you want. If it's lousy code, people will tell you. People will even rewrite it largely for you if they get inclined to do so. As you know, that latter method doesn't ultimately help you.
My points more clearly. Reverse pseudocode of your program:
Code:
main program
Call my_function() and save the result
Output some information
Call my_function() and don't save the result
if (result is 'd') then
output that and exit 0
fi
if (result is 'e') then
output that and exit 1
fi
if (result is 'f') then
output that and exit 2
fi
if (result is 'g') then
output that and exit 3
fi
if (result is 'h') then
output that and exit 4
fi
if (result is 'i') then
output that and exit 5
else
exit 6
fi
end main program
function myfunction()
output some information
read a character
output information, including the character read in
return the character read
end myfunction
You don't need to create a function to call scanf(), and if you noted above, you don't need to call myfunction() twice while not saving the result the second time.
This actually may be a large point. The line showing:
Code:
char_in = myfunction();
You've called it. Boom! You're done needing to call it. Why do you call that function again two lines further down? Do you misunderstand that very important point? Because if you do, there's a moderate problem. When you have myfunction() in a line of code, as it shows the first time and also as it shows the second time, it is being called each time. Just so happens the second time it was called, you're not assigning the output of myfunction() to anything. Pointless and confusing, because it will prompt someone for a second character input, which they'll have to do, and the final output result will match the first character entry they did the last call to that function.
Other points:
Your if-if-if-if ... else is very poor. There can be if-elseif-elseif-elseif-else, or you can use a switch statement.
Printing out explicitly based on your test is 'so-so' in my opinion. I'd rather print out exactly what I received back, %c versus literally coding it into a statement.
Multiple exit points are bad in my book. Better to assign the various return values to a variable, get through all the if-tests or switch statement, and then exit using the return value variable.
Conclusion
Now ... I KNOW what you may say here. All fast talking, stuttering, exonerating statements from you. "That-that-that's because I kept editing that same example a lot, it didn't do that at first, it did something else!" "That's why it looks so bad!" "That extra function call was leftover and I just didn't erase it!" "I would never do that normally!" (But you did)
This is why I'm telling you to be more organized about this learning project.
Much like you'd recommend to a Linux Newbie who was "all over the map" messing up a simple install. You'd say, "Hey! Whoa! Go back and start at square 1 and stop jumping right to square 578! Or at least don't skip the large majority of the steps between."
I have been following this thread but with too many comments and opinions to make, and limited time to reply during the week. I had in mind to try to work up a useful reply over the weekend, but rtmistler has excellently covered just about every thing I wanted to say!
To summarize:
* Design your project before you begin writing code!
* Organzie your code and your learning experience!
* Write - and keep - your own specific example code, understand it thoroughly, maintain it and use it for future reference!
* Learn the little bits first, in isolation and completely - types, I/O, return values - all the things you have been struggling with in aggregate!
Take at least as much time reading rtmistler's reply as he must have taken to write it! Take it to heart!
Instead of trying to get someone else' possibly poorly writtin example "program" to work, try to understand and write your own examples for each of the lowest level concepts that keep recurring - types and comparison vs assignment for example. If you hit the same problem more than once, take that as strong evidence that you did not understand it the first time! Stop right there, search for the specific term at hand and write a simplest example which will let you explore how that specific thing works... move on to others only after you can almost reflexively get the first one right!
And with each item, comment your own examples clearly when the little light upstairs comes on! Translate that "Aha!" moment into typed text which you can refer to in future!
By the way, everyone who has participated in this thread has offered excellent advice - much of which should be considered at length, not received as quick answers! I suspect that you will return to this initial experience and this thread many times in future and think, "Oh! So that is what they meant...".
Stick with it! Slow down, it will take some time! Make the most of your learning time by thoroughly polishing each nugget as you find it before putting it on the shelf and looking for another!
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881
Original Poster
Rep:
rtmistler,
I was hoping to hear from you, and yes, your advice is worth taking notice of. I'll say a few things;
I am not ignorant of the fact I've only just started my first serious attempt at C.
I'm not expecting to be able to write anything useful or even just half properly for quite some time yet.
I realize that like with any other thread here; we all have a choice as to what we reply to and what we don't.
I seriously doubt you would be replying if you were not interested in trying to help me learn.
I do totally agree with everything you have said, and very much thank you for offering that advice.
I was hoping to hear from you because I know you (like astrogeek) have no doubt many years worth of experience, and this is exactly why I want to hear from people just like yourselves. Because let's face it: my experience with C is non-existent.
And I would like to learn to do it properly, and not by half's - as what is the point in even trying if you ain't interested in doing it properly? To me there's no point in that at all, and in that case I may as well just forget about it. So I agree that the organizational aspect of it is just as important as understanding the code. I just wanted to get a feel for it, and was thinking that I should try and learn one thing at a time (as astrogeek was talking about above in terms of understanding one thing, and then moving onto something else). And yes, I created a folder called "old" and moved my previous "attempts" there.
So the bottom line is that, I will be taking your advice. I've attached a c file, not because it works or even compiles (I don't know if it does or not - I haven't checked - and that's not the point of posting it either), but because I read the link you posted about formatting, and I want to try and get that right. I was wondering if you could let me know if the formatting is right or not.
astrogeek, Thanks for taking an interest in this thread. I also value your advice as well, and I thank you taking the time to give it to me. As I know like rtmistler, you know your stuff when it comes to this as well, and probably also have many years of experience too. So for that reason it's really good to hear from the both of you, and I also take your advice too.
I don't plan on doing any coding over the weekend - maybe just some reading and that's it for the weekend.
Thanks again to the both of you, and everyone else who's taken the time to help as well.
// before main
// declare the function
char myfunction (); // char return type, no parameter
This is actually not correct. This declaration is a function which returns char and takes unspecified parameters. This is why earlier in the thread I recommended always using explicit void for functions taking no arguments as in:
Code:
char myfunction(void);
This way there is no need to worry about difference in what empty argument list means in function declaration and function definition. That understanding may wait for later.
Thanks for that info about void arguments, mina86. I totally agree... except that for this new programmer I wanted to keep it simple right now. For what it's worth, before posting that code fragment, I looked up the risks of omitting the void keyword, and I confirmed that it compiled without warnings on my system.
I prefer to indent 3 or 4 white spaces, never use tabs in C code, and put code in brackets even if it is a one line if-statement. I use block function headers, type-defined variables from a common include file and try to code single-entry-single-exit functions.
K.I.S.S. - Keep It Simple ... Keep It Readable
Don't post small clips of code as attached txt files, my systems (multiple) all open then with a variety of programs. Post your short code clips where you have questions, within [code] tags. (There's a link in my signature which explains how to do that )
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881
Original Poster
Rep:
Quote:
Originally Posted by rtmistler
Everyone has different code format preferences.
I prefer to indent 3 or 4 white spaces, never use tabs in C code, and put code in brackets even if it is a one line if-statement. I use block function headers, type-defined variables from a common include file and try to code single-entry-single-exit functions.
K.I.S.S. - Keep It Simple ... Keep It Readable
Don't post small clips of code as attached txt files, my systems (multiple) all open then with a variety of programs. Post your short code clips where you have questions, within [code] tags. (There's a link in my signature which explains how to do that )
Thanks RT!
While I've re-posted what I posted before in the txt file, I'm not quite sure I completely understand what you're saying. I understand your point about not using tabs, so I haven't this time. But I'm not sure what brackets you mean, and putting it into them. And exactly what do you mean when you say "block function header"? And by function header, do you mean the the line that describes the name of the function, with the statements just below that, that form the group of statements that make up the function?
Also, based on what I've posted below; do you think I'm on the right track here ? Because while I think I might be, I'm really not sure if I am or not.
Code:
// headers
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdlib.h>
// variable declaration
int a_var;
// start of main program
int main()
{
// print a message on the screen
puts("blah blah blah");
// set a condition, where if a_var is more (greater than) 100, print a message to the screen
if (a_var > 100)
{
puts("if statement true");
}
// if the condition is not true, then print a message to the screen
else
{
puts("if statement false");
}
return 0;
}
// end of main program
P.S. The book I was referring to is "Programming in C" by Stephen G. Kochan.
Small world. I learnt from the 1988 "Revised Edition" (green cover) of that book, which was pre-ANSI K&R syntax. I still keep it on the bookshelf beside me. It's a very gentle introduction to the language well suited to beginners.
I agree with Mechanikx, you'd be better off with a different source. The "tutorial" you linked looks like a good reference to keep at hand for when you need a quick reminder once you're up and running but from the quick glance I took it seems to throw too much detail at the reader all at once to be a good "introduction piece".
Keep at it, you'll get there, and C is a useful tool to have under your belt.
Distribution: Currently: OpenMandriva. Previously: openSUSE, PCLinuxOS, CentOS, among others over the years.
Posts: 3,881
Original Poster
Rep:
Absolutely agree with you GazL, that tutorial is just crap. Good to hear from you.
I've just been doing some re-reading of that same near useless tutorial I started off with, and have been trying to understand what didn't make sense to me before, particularly the different "data types". Now, under "Enumerated types" it talks about "discrete integer values", I've been trying to understand exactly what that means, and I still don't get it.
So I looked up the meaning for "discrete", and it says;
Quote:
individually separate and distinct.
That by itself, I get it. But in relation to "discrete integer values", I still don't understand exactly what that means. I get that an "integer" is a number without the fractional part. But I still don't understand why I would use that or what that exactly means. I've tried looking at various sites (some of which I ended up just closing, because they just confused me even more), but it's still not clear to me exactly what that term means. Please bear in mind that I'm absolutely hopeless when it comes to maths, so it's just going to fly straight over my head if you are not clear about exactly what I'm failing to understand here. Could someone give me an example/explain exactly what that term means in relation to C? Why would I use an "discrete integer value" data type? I don't get it.
Last edited by jsbjsb001; 12-15-2018 at 08:32 AM.
Reason: typos as per usual
Mathematics has concepts like real numbers, continuous/discrete variables and other such confusing terms, but as far as C is concerned one simply doesn't need to worry about such things. Seems that tutorial is using unnecessarily flowery language.
Seriously, go find yourself the Kochan book. I won't provide links here for obvious reasons but some illicit copies can be found in pdf form with a quick google search; however, if you do find a copy that way and find you like it, I'd encourage you to do the right thing and buy yourself a real copy.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.