• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 510
  • Last Modified:

Learning C programming when someone already knows C++

Is it a good idea to know C when someone knows C++. I heard its very confusing to know both the languages together. However if needed be, how difficult it will be for someone to learn C when he already knows C++. (100 points)

Can someone point me to a very good website which lists all the differences between C and C++, like differnces in filehandling, using functions etc (200 points)

Finally I know the main differences that in C we have structs and no classes. How can we implement the functionality of private and public keyword while writing a C program. I mean how do we implement data security in C programming (200 points)
0
anshuma
Asked:
anshuma
  • 5
  • 4
  • 2
  • +4
5 Solutions
 
grg99Commented:
Q1:
     It's rather confusing.

   You have to forget all about classes, inheritance,  the std library, iostreams, cin, cout, new, delete,  references, namespaces, overloading.

You have to learn about char[] strings, passing pointers instead of references, the stdio library: open read, write,  fopen, fread, fwrite.  Not to mention printf, scanf, and the like. Oh, and the dynamic memory things:  malloc, free,

Q2:
    You can't hide data too easily.  You can "hide" the data by only divulging something like:  

struct { int YouCanSetThisInt;  char YouCanSetThisCharToo; double Result;  char Dummy[100]; } TheData;

but in your private code you use the full definition:

struct { int YouCanSetThisInt;  char YouCanSetThisCharToo; double Result;
/* hidden vars: */
int SecretVar1, SecretVar2, ...;
 } TheData;

0
 
baboo_Commented:
anshuma:

Hello!  Hope everything's going well learning C.  

Question 1:

Learning C when you know C++ is more difficult than learning C++ when you know C.  Now, there's nothing you can do in C++ that you can't do (with a bit more difficulty) in C.  C++ provides support for a lot of things that enforce good programming practices (i.e., Classes, and data encapsulation, etc.)  You can do some pretty ugly and questionable things in C, but if you're careful and fastidious, you might (might...) find that programming in C is a bit more pleasing in an exsistential sense....  A lot of the additional functionality that comes with C++ is in the form of the standard template libraries - classes someone else wrote for common tasks.  Those aren't there in C, and you're likely to miss them.  But it's not too confusing to keep the 2 separate.  

My advice would be this:  Start fresh, as though you're learning C as a new language.  It'll be easiest this way, because you'll start recognizing syntax that's the same as C++.  But you won't get into the trap of assuming that you have a certain ability when you don't.  

The best book I can suggest is Kernighan & Ritchie's The C Programming Language.  It's very short (because C is very simple), and contains both tutorials and every technical thing you might want to know about the language.  My favorite book for C - I still use it when coding from time to time!


Question 2:
Here are some sites that highlight the differences between C and C++.  The last one has a concise table of syntax differences, including file handling.

http://people.cs.uchicago.edu/~iancooke/osstuff/ccc.html
http://www.rit.edu/~jpw9607/ctut/
http://fechner.ccs.brandeis.edu/programming/cvsc++.html
http://faculty.cs.tamu.edu/teresa/cpsc211/ps/CppToC.html



Question 3:
Data security and things like this are only an issue when you're writing code for others to use.  It works the same as in C++.  You write code and present an interface that give access to only those things you want the users of your code to have access to.  Say you're implementing an abstract data type for, say, a bitstring.  You can write methods that create/access/mutate the data itself without giving your users access to the data member itself.

The way you do this is to write a C source file (your implementation) and a separate header file (your interface).  Now, there's nothing to stop someone from looking in your source file and grabbing the name of your data member to use in their own code, but that's dirty pool anyways...   If you wanted to be even more safe, you could compile your source code as a dynamic linkable library, so others don't have access to your source to find your private members (just one possiblity).

Just to be clear about data "security,"  the only "security" that C++'s classes and private data members enforces is the security of good programming practices.  Again, C will let you get away with bad practice if you're not careful.
 
Here's someone else's example of data encapsulation:
http://www.csd.uwo.ca/%7ejamie/C/encapsulatedC.html#Example

I hope this helps!

baboo_
0
 
efnCommented:
> Is it a good idea to know C when someone knows C++.

It depends on your circumstances and goals.  If someone will (or even might) pay you for programming in C, it's good to know it.  If you want to collect C++ trivia, you might want to know how it overlaps with and differs from C.  I doubt that knowing C will make you a better C++ programmer, or even a better programmer in general.

Another way to fake private member variables is to include in a structure a "handle" of some kind.  It can be an index into a private array or a pointer to a dynamically allocated object.  The client software can't do anything with it but pass it to functions that know how to use it.

You can fake private member functions by declaring them static.  Then they are only visible within the same translation unit, usually the source file in which they appear.  This is also how you would make the private array I mentioned above.

As baboo_ said, the security is not tight in any case.

--efn
0
Live webcast with Pinal Dave

Pinal Dave will teach you tricks to help identify the real root cause of database problems rather than red herrings. Attendees will learn scripts that they can use in their environment to immediately figure out their performance Blame Shifters and fix them quickly.

 
jhshuklaCommented:
I believe that public/private are supported in structs; just that default is public in structs and private in classes.
0
 
efnCommented:
> I believe that public/private are supported in structs; just that default is public in structs and private in classes.

True in C++, not in C.
0
 
avizitCommented:
>>How can we implement the functionality of private and public keyword while writing a C program.

If you are trying to do that in C, you are using wrong tools for the purpose.  The key to C and C++ is that both are different tools for different purpose. even though both the high level computer languages.

I doubt you there is any language feature in C which will let you have the functionality of private and public keywords.  
0
 
skypalaeCommented:
> I doubt you there is any language feature in C which will let you have the functionality of private and public keywords.  

Yes, there is. Baboo has mentioned that.
Every class would have it's own .c and .h files. In .c there would be all member variables and methods. In .h there would be public members only (due to good practices there should not be public variables, but who is that good). After compilation you get .obj which is encapsulated enought to prevent others from peeking into your code (and using the private members). And it's still linkable into the rest of code. However you still have to implement other features like name mangling (which prevents from duplicate names) and thiscall mechanism (which actually passes the class data as the very first argument)

example:

mylist.h

struct list ;
struct list *list () ; // constructor
void _list (struct list **list) ; // destructor


mylist.c

#include "mylist.h" // can be ommited, but it's good practise :)
#include "malloc.h"

struct list {
    int length ;
    int *data ;
};

struct list *list () {
    return (struct list *) malloc (sizeof (struct list)) ;
} ;

void _list (struct list **list) {
    if (*list)
        free (*list) ;
    *list = NULL ; // just some cleanup .. however C++ doesn't provide this
}

main.c

#include "mylist.h"

int main (int argc, char **argv) {

    struct list *l = list () ; // create new list

    _list (&l) ; // release it

    return 0 ;
}



Cheers! S.
0
 
skypalaeCommented:
Well .. I forgot one more (important) method:

.h
int length (struct list *) ;

.c
int length (struct list *list) {
    return list->length ;
}


main.c:

int len = list->length ; // error C2037: left of 'length' specifies undefined struct/union 'list'
int len = length (list) ; // OK

S.

0
 
avizitCommented:
>> I doubt you there is any language feature in C which will let you have the functionality of private and public keywords.  

>Yes, there is. Baboo has mentioned that.
>Every class would have it's own .c and .h files. In .c there would be all member variables and methods. In .h there would be >public members only (due to good practices there should not be public variables, but who is that good). After compilation you >get .obj which is encapsulated enought to prevent others from peeking into your code (and using the private members). And >it's still linkable into the rest of code. However you still have to implement other features like name mangling (which prevents >from duplicate names) and thiscall mechanism (which actually passes the class data as the very first argument)

What you mention is not the functionality provided by the "public" and "private" keywords. If you keep your variables in .c files and compile to the object files, those are still accesible , provided you know its there. While using the private keyword, you know its there but another function cannot access it.  

0
 
skypalaeCommented:
avizit,

yes, the secret is .. "provided you know its there". Yet then you have to declare the struct (with all it's variables) and then access them. That's really not good practise (as we're talking about it all the time).

Using the same dirty practises, you can access the private members of C++ classes same as easily (provided you know they're there).


class C {
public:
    int pub ;
private:
    int priv ;
};

class MyC {
public:
    int pub ;
    int priv ;
};

int main (int argc, char **argv) {

    MyC *c2 = (MyC*)new C() ;

    int b = c2->priv ;

    return 0 ;
}

S.
0
 
baboo_Commented:
Look:

This whole conversation about "data security" and our dread fascination with encapsulation is ignoring a fundamental difference between C and C++.

C was created in Bell Labs, by computer scientists, for computer scientists.  It was created to be Turing-complete, functional, powerful, and easy-to-use (when compared to, saaaay, assembly).

C was never initially intended to write the things that C++ is used to write, such as huge business apps, or Microsoft Word, or big multi-programmer projects.

C++ is an extension of C (well, you could almost say that it's a proper superset... almost) that's designed to be used by large groups of programmers, of varying skill, and with various bad coding habits, so that they can work together to create something marvelous, like a big business application, or Microsoft Word.  The concept of OOP is a neat concept that's another way of translating real-life problems into programmatic solutions.

But, ultimately, when it's all said and done, it's all just pushing bits.  *how* you get the coding done makes almost no difference anymore, except to save you the headache of debugging a project that spanned 2 years and 100 different coders.

The fact that C lacks some of the formalizations of "class" and "object" is simply a function of its primary use:  It was, and is, primarily used for  small, academic projects.  It's like Robert DeNiro says in Ronin, "They're all tools, like in a toolbox.  I just pick the tool that's right for the job."

C++ is good for uniformity between different programmers.  It ENFORCES the use of good practices among programmers that might not be very good programmers at all.  It's the computer science world's way of trying to standardize coding practices and procedures.  We, as computer scientists, are living in the early years of our field.  Compare what we do to, say, what engineers do.  If you took any bridge in the world, and any civil engineer in the world at random, that engineer could explain to you, simply at a glance, exactly how that bridge works, why the engineer that built it did what they did, why they used the material they used, etc.  But if you took any program in the world and any programmer at random, there's a better than 99% chance that the programmer would end up saying something along the lines of, "Uh - that was coded by an insane person, wasn't it?"

Why the difference?  Because the science of bridge building has been around for centuries.  Civil engineers have winnowed away the techniques and materials that are unsuitable for bridge building, and settled on a very small set of items and techniques, that all work, and work well.  We haven't done that yet with CS.  Someday, there may be a standard "Database Language" and a standard "Networking Language," etc., and standard techniques that are so well-defined as to be canonical.  

But for now, we're in the process of getting there, and the step from C to C++ is a step in that direction.  



Woah.  Where'd that come from?

Uhh..  I'm confused.  What were we talking about again?

baboo_
0
 
baboo_Commented:
O yeah.  This "public/private" stuff.

Look - the reason that compiler-enforced data encapsulation was invented was to MAKE you program a certain way - the OOP way.  There's no rule that says OOP is the best way, and in fact, there are projects (albeit smaller ones) where procedural programming is the way to go.

On the other hand, there's nothing that stops you from coding according to OOP practices in C.  The only difference is that you have to be careful how you use data - the compiler won't tell you when you're doing something that's "not quite OOP."  It'll let you do your bad thing, and compile merrily away.  And that's the point of classes, objects, encapsulation, and OOP in C++ - to take away your ability to program badly and dangerously.

You should be less concerned with the fact that you can't make the compiler remind you how to program well, and more concerned with simply learning how to program well.  

Let's also not misunderstand the term "security" as it applies to this discussion:  We're not talking about security like, "bank security" or "credit card transaction security."  We're talking security like "security blanket" or "the reasonable assumption that we're not doing anything too stupid."  The bottom line is that C doesn't do the public/private thing for you - you have to make up your mind how you want to encapsulate your data, and then make yourself stick to it.

So, does knowing C make you a better C++ programmer, or does it make you a better programmer in general?  Well, think about it this way:  There are 2 samurai.  One practices all day long with a wooden sword.  One practices with a sharp blade.  C is like the sharp blade, and C++ is like the wooden sword.  Can you infer anything about the relative skills of the 2 just with this description?  No, of course not.  Give them both wooden swords, and the one who practices with the wooden sword could very well kick ass (or, then again, he might not) - the point is, you can't say.

But you can rest assured that the samurai who practices with the sharp blade knows how to swing the sword without cutting himself.  That's what knowing C will do for you - it'll help you learn not to "cut yourself" when coding.

baboo_
0
 
skypalaeCommented:
baboo, great. i haven't read such long comments for a long time. however, they're very true.
the discussion turned a little to a discussion if OOP is safe or not. i've been programming in assembler using OO techniques and surprisingly it was possible. OO is language independent and you can use any computer language (except Turing :)) together with OO. only some compilers can check the "good practise" for you.

i would say that in C you can manually do everything that C++ does automatically for you.

classes: use structs instead. dont ever access private fields (even if it is possible) !!! (you can make some fields private by using previously mentioned methods)
inheritance: put base class as first member of struct. that way you can cast. multiple inheritance won't work (but who needs multiple inheritance anyway)
polymorphism: do your own name-mangling. something like object_function_typ1_typ2 (args). it will make you type lot more text, but you will have polymotphism
templates: same as polymorphism

S.
0
 
baboo_Commented:
absolutely - my buddy wrote an entire evolutionary computing library that was perfectly OO in C.  It's possible - like skypalae said.

Ah... anshuma, are we answering your question, by the way?  (or are we digressing?)  Sorry...

baboo_
0
 
anshumaEngineeringAuthor Commented:
Well yeah, you experts have been helping me alot. However I have learnt t=what learning C takes, I will have to delve deeper into pointers when I am using functions. All my previous projects have been in C++ and Visual Basic.

I have found C to be time consuming and with a cryptic syntax. It requires us to memorize and get into intricate details which are off course a pain when time to produce is important like printf("The Number=%d",alpha) seems really awkward instead of cout.

0
 
skypalaeCommented:
anshuma,

do you think that C# system.console.print ("number = {1}", alpha) is less cryptic? (i'm not C# programmer, so the syntax can be bit wrong)

To help you with pointers a bit, I must say that they're exactly the same pointers as in C++. Thus if you write:

    int *a = new int ;

it's same as if you write

    int *a = (int *) malloc (sizeof (int)) ;


and the opposite operation

    delete a ;

looks in C like this:

    free (a) ;

that's all about creation and releasing objects (see .. it doesn't matter if the object is a structure or integral). you can see that the functionality stays (almost) the same, it just uses different words for same action

for classes (structs) one more thing should be provided. that's the constructor and destructor.

    Class *c = new Class (init_args) ;

will look like this:

    Struct *s = (Struct *) malloc (sizeof (Struct)) ;
    struct_init (s, init_args) ; // this is my initialization function

and similar, the destructor would look like this

    struct_fin (s) ; // this is again my function
    free (s) ;


the references in C++ is nothing more than fooling the compiler that the variable isn't a pointer. you can write (functionally) same pieces of code in C and C++, compile them, run them in debug mode, press Alt-8 and check the resulting assembler code. It will look same.

void cpp_fun (int &arg) {
    arg = 1 ;
}

void c_fun (int *arg) {
    *arg = 1 ;
}

....
int a ;
cpp_fun (a) ;
c_fun (&a) ;

Again, you can see that there's very little difference between C and C++. Only when you declare a reference in C++ you have to declare a pointer in C. And when you access a reference in C++ you have to access the dereference in C. and when you call by reference, you have to make the pointer from the argument (again the same applies to structs, arrays, function pointers etc.).


I personally think that moving from C++ to C is easier than the other way. You can do same things in both languages (only the function names are different). But when you don't know anything about OO it's real pain to understand it good.

S.
0

Featured Post

Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

  • 5
  • 4
  • 2
  • +4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now