GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 17-Jan-2009, 02:50
zatora zatora is offline
Member
 
Join Date: May 2008
Posts: 110
zatora will become famous soon enough

Argc, Argv[] and Command Line


Hi all,

Question 1:

i was reading some documents online, i have encountred this statement
int main(argc, argv[]) and the topic was reffering to command line so i did not know what is command line arguments and the argc, argv[]
(please if anyone can help with defining these terms and why arv[] has the brackets like an array?

Question 2:

Does anyone know what is the void type i ve seen this before
int funct(void *) : so i said what a newbi will do with that?

Please if you can provide an example implementing a response to the 2 questions that will be appreciated ?
  #2  
Old 17-Jan-2009, 07:36
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 226
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Argc, Argv[] and Command Line


Quote:
Originally Posted by zatora
i did not know what is command line arguments and the argc, argv[] (please if anyone can help with defining these terms and why arv[] has the brackets like an array?

CPP / C++ / C Code:
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    for(int i = 0; i < argc; i++)
    {
	cout << "argv[" << i << "] == " << argv[i] << endl;
    }
    return 0;
}

Output:

Code:
$ ./cli_args argv[0] == ./cli_args $ ./cli_args 1 2 3 this is not the end of the world as we know it. argv[0] == ./cli_args argv[1] == 1 argv[2] == 2 argv[3] == 3 argv[4] == this argv[5] == is argv[6] == not argv[7] == the argv[8] == end argv[9] == of argv[10] == the argv[11] == world argv[12] == as argv[13] == we argv[14] == know argv[15] == it.

argc is an integer count of the arguments given on the command line when invoking the program. The "c" part is count of the "arg" part which is argument(s). argv[] is a variable length (the "v" part) array that is created at runtime based on the command line invocation. It is an array of char pointers whose number (count) of elements is exactly argc.

Note that the program name passed to the loader is always the first (zeroth index of the argv array) argument.

Quote:
Originally Posted by zatora
int funct(void *) : so i said what a newbi will do with that?

...probably screw it up. The "void" type is "typeless." In C, it is also a means to provide polymorphic behavior in that any type's address can be passed into a function that takes a void*. It is up to the implementation to cast the type to the proper type and use it as intended.

Quote:
Originally Posted by zatora
Please if you can provide an example implementing a response to the 2 questions that will be appreciated ?

CPP / C++ / C Code:
#include <iostream>

using namespace std;

enum KNOWN_TYPES { INT = 1, FLOAT = 2 };

typedef struct UnknownType
{
    enum KNOWN_TYPES ktype;
    void* pdata;
} UNKNOWN;

void work(void* p)
{
    UNKNOWN* punk = (UNKNOWN*)p;
    switch(punk->ktype)
    {
	case INT:
	    cout << "The Integer value you entered was: " << (*(int*)punk->pdata) << endl;
	    break;
	case FLOAT:
	    cout << "The Float value you entered was: " << (*(float*)punk->pdata) << endl;
	    break;
	default:
	    break;
    }
}

int main()
{
    int v;
    float f;
    
    cout << "1 = Integer\n2 = Float\n\nPlease Enter Type to be entered: ";
    cin >> v;
    UNKNOWN unk;
    unk.ktype = (KNOWN_TYPES)v;
    switch(unk.ktype)
    {
	case INT:
	   cout << "\nOkay, please enter an Integer: ";
	    cin >> v;
	    unk.pdata = &v;
	    break;
	case FLOAT:
	    cout << "\nOkay, please enter a Float: ";
	    cin >> f;
	    unk.pdata = &f;
	    break;
	default:
	    break;
    } 
    work(&unk);
    return 0;
}

Output:

Code:
$ ./void_star 1 = Integer 2 = Float Please Enter Type to be entered: 1 Okay, please enter an Integer: 123 The Integer value you entered was: 123 $ ./void_star 1 = Integer 2 = Float Please Enter Type to be entered: 2 Okay, please enter a Float: 12.34 The Float value you entered was: 12.34


MxB
  #3  
Old 17-Jan-2009, 22:52
ocicat ocicat is offline
Regular Member
 
Join Date: May 2008
Posts: 580
ocicat is a jewel in the roughocicat is a jewel in the rough

Re: Argc, Argv[] and Command Line


Quote:
Originally Posted by zatora
Does anyone know what is the void type i ve seen this before
int funct(void *) : so i said what a newbi will do with that?
As Mexican Bob states, typeless pointers are useful when attempting to write generic code which is not tied to specific types. This is fundamental in C, but somewhat deprecated in C++ (where templates are preferred...). Consider the use of qsort() (which is a classic example of a generic function available in the standard library...):
CPP / C++ / C Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MAX_STRING_SIZE    16
#define ELEMENTS           10

typedef struct {
  char *name;
  char *count;
} fruit;

fruit list[] = { { "apples", "3" }, { "bananas", "2" }, { "grapes", "10" }, { "oranges", "1" } ,
                 { "cherries", "9" }, { "dates", "7" }, { "plums", "8" }, { "pears", "4" },
                 { "cranberries", "6" }, { "figs", "5" } };

void output(fruit[], char*);
int ascending_alphabetic_by_name(const void*, const void*);
int descending_alphabetic_by_name(const void*, const void*);
int ascending_count_by_ascii(const void*, const void*);
int ascending_count_by_value(const void*, const void*);

int main()
{
  output(list, "initial order");

  qsort(list, ELEMENTS, sizeof(fruit), &ascending_alphabetic_by_name);
  output(list, "ascending alphabetic by name");

  qsort(list, ELEMENTS, sizeof(fruit), &descending_alphabetic_by_name);
  output(list, "descending alphabetic by name");

  qsort(list, ELEMENTS, sizeof(fruit), &ascending_count_by_ascii);
  output(list, "ascending count by ASCII");

  qsort(list, ELEMENTS, sizeof(fruit), &ascending_count_by_value);
  output(list, "ascending count by value");
 
  return 0;
}

void output(fruit a[], char *msg)
{
  int i;

  printf("%s\n", msg);

  for (i = 0; i < ELEMENTS; i++) {
    printf("%2d\t%-10s\t%2s\n", i, a[i].name, a[i].count);
  }
}

int ascending_alphabetic_by_name(const void *p, const void *q)
{
  return strcmp(((fruit*) p)->name, ((fruit*) q)->name); 
}

int descending_alphabetic_by_name(const void *p, const void *q)
{
  return strcmp(((fruit*) q)->name, ((fruit*) p)->name); 
}

int ascending_count_by_ascii(const void *p, const void *q)
{
  return strcmp(((fruit*) p)->count, ((fruit*) q)->count); 
}

int ascending_count_by_value(const void *p, const void *q)
{
  int a = atoi(((fruit*) p)->count);
  int b = atoi(((fruit*) q)->count);

  if (a > b)
    return 1;
  else if (a < b)
    return -1;
  else if (a == b)
    return 0;
}
...where execution yields:
Code:
initial order 0 apples 3 1 bananas 2 2 grapes 10 3 oranges 1 4 cherries 9 5 dates 7 6 plums 8 7 pears 4 8 cranberries 6 9 figs 5 ascending alphabetic by name 0 apples 3 1 bananas 2 2 cherries 9 3 cranberries 6 4 dates 7 5 figs 5 6 grapes 10 7 oranges 1 8 pears 4 9 plums 8 descending alphabetic by name 0 plums 8 1 pears 4 2 oranges 1 3 grapes 10 4 figs 5 5 dates 7 6 cranberries 6 7 cherries 9 8 bananas 2 9 apples 3 ascending count by ASCII 0 oranges 1 1 grapes 10 2 bananas 2 3 apples 3 4 pears 4 5 figs 5 6 cranberries 6 7 dates 7 8 plums 8 9 cherries 9 ascending count by value 0 oranges 1 1 bananas 2 2 apples 3 3 pears 4 4 figs 5 5 cranberries 6 6 dates 7 7 plums 8 8 cherries 9 9 grapes 10
This Quicksort implementation doesn't have to be tied to specific types as long as the custom comparison function supplied to it follows the understood dictum that:
  • a positive integer will be returned if the first argument is "larger" than the second.
  • a negative integer will be returned if the first argument is "less" than the second.
  • zero will be returned if the first argument is "equivalent" to the second.
Note that these rules follow the way strcmp() is implemented. The coincidence is intended.

The drawback of dealing with void* pointers is that the compiler is no longer able to discern syntactic errors as can be done in C++ templates. Neither C or C++ compilers can verify the contents found at an address which has been declared as void*. This is one of the leading motivations Stroustrup had in implementing the concept of C++ templates in the first place -- allow the compiler to perform type-checking on generic code since this could save the development time typically expended when trying to debug why execution went into the weeds just because the specified casting was wrong.
  #4  
Old 18-Jan-2009, 08:54
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 226
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Argc, Argv[] and Command Line


Quote:
Originally Posted by ocicat
This is one of the leading motivations Stroustrup had in implementing the concept of C++ templates in the first place -- allow the compiler to perform type-checking on generic code since this could save the development time typically expended when trying to debug why execution went into the weeds just because the specified casting was wrong.

Except that Stroustrup didn't "implement the concept of C++ templates" in the first place, 2nd place or otherwise. Alexander Stepanov did and sent it to Stroustrup who embraced it.

The "butler" STL code is still available from HP, but is now on a new server (and has been for a few years, at least).

None of these points should be taken as a reason to use void* in situations where templates can be used.


MxB
  #5  
Old 18-Jan-2009, 10:16
zatora zatora is offline
Member
 
Join Date: May 2008
Posts: 110
zatora will become famous soon enough

Re: Argc, Argv[] and Command Line


Hi Guys , But i am going to stop here i have a head ache so OCICAT versus Bob Mexican you guys go at it. One more posting like this and i will go back and start a business program and Hell with programming, well that was my impression, although you guys are saying good and valuable information but you are not realizing how a beginner feel when i encounter things like argc and argv[]., suddenly Howard_L (who i thought he was a teacher before posted this)
Quote:
Originally Posted by Howard_L
Quote:
Originally Posted by zatora
i started with visual studio 2008.
So the word console command line arguments are not clear what is a command line
Ah! I think this is a major part of the problem!
The concept of invoking a program on the command line.
You are used to running your C++ programs from within Visual C++, Non??

Well for an example of command line args lets look at our assembly commands.
First in linux we use the xterm terminal.
That is what we call a CLI or Command Line Interface (as opposed to a gui).

In the CLI we would comile our assembly program like this:

as myprog.s -o myprog.o

In that line we are passing 4 arguments:
1) 'as' the name of the program we are calling.
2) 'myprog.s' An additional piece of info to pass to the program.
3) '-o' Another additional piece of info '' '' '' ''
4) 'myprog.o' Another additional piece of info '' '' '' ''

So there are 4 arguments there right? These are the command line arguments.
These will be 'pushed onto the stack' in the reverse order as given. That is # 4 first , then #3, #2 and #1. And along with them one more thing, the argument count.

stack:
arg #4
arg #3
arg #2
arg #1
count (ESP is here at program start).

Now the program ('as' in this case) will be able to get those arguments and use them to compile the program as we requested.

Now the best illustrations of things like this are in assembly and C. C++ just has too much 'automatic' stuff going on to get the idea of what is reallly happening.

So have you compiled a C program on the linux command line yet?
It is much the same as the 'as' line. How a bout a quick 'hello' program:
CPP / C++ / C Code:
/* hello-01.c */
#include <stdio.h>

int main()
{
  printf("hello world\n");
  return 0;
}

/* 
Save this program as hello-01.c

Compile with this line:
gcc -Wall -W -pedantic  hello-01.c  -o hello-1

Run program with this line:
./hello-1
*/
So you see basically the same as the 'as' program.
Can you do that?
Next we would make one

Now you could invoke the program with command line arguments except that it is not made to handle them and so they will have no effect.. So to use them we would do something like what MBob posted for you except in a C version with a little more output:
CPP / C++ / C Code:
#include <stdio.h>

int main(int argc, char* argv[])
{
  int i;

  printf("There were %d arguments given: \n", argc);

  for(i = 0; i < argc; i++)
  {
    printf("argv[%d] is stored at address: %p  : %s \n", i, (void*)argv[i], argv[i] );
  }
  return 0;
}

/* 
gcc -Wall -W -pedantic clargs-01.c -o clargs-01

./clargs-01 these are CL arguments

Sample output:

C:\hlenderk\cprogs> clargs-01 these are CL arguments
There were 5 arguments given:
argv[0] is stored at address: 003E3B59  : clargs-01
argv[1] is stored at address: 003E3B64  : these
argv[2] is stored at address: 003E3B6B  : are
argv[3] is stored at address: 003E3B70  : CL
argv[4] is stored at address: 003E3B74  : arguments

*/
Thanks all for the help, as I said before i will always appreciate someone who takes passion ,time of his own life and we all know how hard is our life these days.
Special Thanks to Howard_L:" There is the spirit of a teacher in you"
and Viva Lunix ( Windows Forget about it)
"This copyright of this post Howard_l,and whom he quoted from ..."
  #6  
Old 18-Jan-2009, 12:10
ocicat ocicat is offline
Regular Member
 
Join Date: May 2008
Posts: 580
ocicat is a jewel in the roughocicat is a jewel in the rough

Re: Argc, Argv[] and Command Line


Quote:
Originally Posted by Mexican Bob
Except that Stroustrup didn't "implement the concept of C++ templates" in the first place, 2nd place or otherwise. Alexander Stepanov did and sent it to Stroustrup who embraced it.
While I agree that Stroustrup did not invent the concept of templates (which were already available in Ada as generic packages...), he was very much involved in deciding how templates were to be implemented (which was my choice in words...) & integrated into C++ proper. Yes, Alex Stepanov did make proposals (& most notably later for the STL itself...), as to how templates were to be implemented, but the process was shared amongst many, & not solely due to Stepanov's work alone as you elude. For more information, see Section 15.2 of The Design & Evolution of C++.
  #7  
Old 18-Jan-2009, 13:28
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 226
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Argc, Argv[] and Command Line


Quote:
Originally Posted by ocicat
he was very much involved in deciding how templates were to be implemented (which was my choice in words...) & integrated into C++ proper.

Uhh, that's not exactly what you wrote. You said "implement the concept of C++ templates," which is, IMO, a somewhat different thing than actually implementing templates using the C++ language and relevant compiler(s). I do not want to get into a semantics "war" with you or anyone else. My primary point was to ensure that Alex received proper credit for bringing the concepts of templates to C++. In the C++ community, introducing a new language feature would obviously solicit the input of its creator, particularly with regard to how to best facilitate the integration of it into the language. However, I strongly support the notion that Stepanov pioneered templates and championed their adoption in C++ with the active support of the C++ community.

To me, that is "implemented the concepts," which is probably just a semantic nuance rather than what you meant to say. However, because you didn't mention Stepanov, I thought that it was appropriate to bring it to attention. I think that if you objectively re-read your post, that you will find that it is entirely possible for newbies to mistakenly assume that Stroustrup "invented" C++ templates for lack of a better reference.

Perhaps my choice of words and presentation method suggests a confrontational position, which is certainly not intended. It is my only intention to contribute where possible, and I definitely do not know all of the facts involved in the evolution of C++ templates.


MxB
  #8  
Old 18-Jan-2009, 13:46
zatora zatora is offline
Member
 
Join Date: May 2008
Posts: 110
zatora will become famous soon enough

Re: Argc, Argv[] and Command Line


Why don't you guys provide some example so we can follow this french-russian discussion ? ?
  #9  
Old 18-Jan-2009, 14:57
Mexican Bob's Avatar
Mexican Bob Mexican Bob is offline
Member
 
Join Date: Mar 2008
Location: Chicxulub, Yucatán
Posts: 226
Mexican Bob is a jewel in the roughMexican Bob is a jewel in the roughMexican Bob is a jewel in the rough

Re: Argc, Argv[] and Command Line


Quote:
Originally Posted by zatora
Why don't you guys provide some example so we can follow this french-russian discussion ? ?

Do you speak French or Russian? If not, maybe there is a possibility that you're not going to be able to follow it anyway?

The short answer is that you're probably not ready yet for templates. That isn't to suggest in any way whatsoever that you shouldn't review templates or learn about them. It is only that you have more fundamentals to discover before you engage in the "advanced features" of C++.

One of the "issues" with advanced features of any programming language is the mindset or, more loosely translated, the "position from which you consider the details of" the various technologies involved in a particular feature. With these "technologies" is often a LOT of concepts that relate to the general problem domain of generic programming and/or reusable code in C++. These issues are often not easily understood even by seasoned programmers who have a good grasp of the fundamentals of the syntax of the language and/or the notions commonly associated with "procedural programming" for a given language syntax.

This is incredibly common in C and those who "know C" but fail miserably in C++ without even realizing it. This is the "C++ as a better C" metaphor, but it isn't always truly the case--in terms of programmer experience--because there are appropriate times when using C++ as a better C is, in fact, a true benefit and not merely a representation of an inexperienced programmer "trying" to do what is considered to be "right."

Newbies are expected to have no real understanding of many of the advanced concepts of C++. This is akin to suggesting that a 2nd year med student isn't expected to know the details of complex surgical procedures, even if the "scrubs" uniform doesn't differentiate the individual from those with experience. If I put on a pair of scrubs, I could easily be mistaken as a doctor whereas I have absolutely no training at all in the medical profession outside of basic CPR and other, similarly related, life saving techniques. The idea of drilling holes into someone's head would definitely be "scary" for me.

Additionally, I wouldn't think that my brain surgeon would be hacking C++ code for the nearby timekeeping device that records staff labor on a particular hospital floor.


MxB
  #10  
Old 18-Jan-2009, 20:32
ocicat ocicat is offline
Regular Member
 
Join Date: May 2008
Posts: 580
ocicat is a jewel in the roughocicat is a jewel in the rough

Re: Argc, Argv[] and Command Line


Quote:
Originally Posted by zatora
Why don't you guys provide some example so we can follow this french-russian discussion ? ?
If you still have textbooks from whatever C++ classes you have taken, you will most likely see chapters on template classes & the Standard Template Library (STL) there. I would be surprised if you don't given that you have previously mentioned that you have taken at least two classes & the last being a data structures class.

Yet for an example, consider a linked list as a data structure. The code surrounding the linkage is the same regardless of what data is actually stored at each node. This would be a perfect candidate for being written as a template class (which is a class that is parameterized -- meaning that the types of various internal data can be specified after the class has been written...). Thus, such a class needs to only be written once as a template class as opposed to being rewritten over & over for each specific use within an application.

If you are unfamiliar with the STL, this is one of the last features added to C++ in 1994. This is an extensible framework of common data structures which can easily be integrated into most C++ applications. Wikipedia has an entry describing this further:

http://en.wikipedia.org/wiki/Standard_Template_Library

Given that lists are part of the STL, writing custom code to implement linked lists now isn't required at all.

Alternatives to STL include the Boost & STLSoft libraries. The reason alternatives arose is because many compilers in the ~1995 - 2005 era still had issues compiling the STL successfully given that many changes to templates was made in the standard, & it took time for the various compiler vendors to catch up with reliable products.
 
 

Recent GIDBlogOnce again, no time for hobbies by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 03:04.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.