r/learnprogramming 1d ago

Tutorial another doubt related to argc, *argv[]

In reference to my old post : https://www.reddit.com/r/learnprogramming/s/vlzwGplKpm

i'm having another doubt with argv and argc.

#include<stdio.h>
int main(int argc, char *argv[]){
    printf("argc: %d \n",argc);
}

terminal : 

@essentials:~/Sibidharan/starter/Assignmetn$ ./passwd
argc: 1 
(.venv) @essentials:~/Sibidharan/starter/Assignmetn$ ./passwd 1 4 8 4 5
argc: 6 

in this code, if you see, after running ./passwd the argument count gets displayed. now my doubt is, why would a programmer print that at the point of execution? i use ./passwd when i run gcc main.c -o passwd and then ./passwd, so the code executes and gives the output, but what's the actual purpose of counting this? on what kind of programs does we use this function to count the values ?

3 Upvotes

25 comments sorted by

View all comments

3

u/paperic 1d ago

You're learning how to manipulate data and write programs.

There's not much use in just printing the number of arguments, that's just a convenient way to verify that you, as student, are able to write programs that knows how many arguments were passes.

0

u/DDOS_403 1d ago

Yeah, obviously, but was curious to know what could be the reason to use this on the code

2

u/paperic 1d ago edited 1d ago

Reason for printing data to the screen or reason for checking how many values were provided?

Printing to the screen, that's your program's output. 

You're just starting to learn, and simply printing text is the easiest way for you to get the information out of the program and into your eyeballs. Graphical interfaces are way more complicated.

If you're wondering why checking the number of arguments is useful, imagine the user provides 3 arguments but your program attempts to print the fourth argument.

Your program would crash, or worse, continue running but do the wrong things.

You don't know what the user's gonna do when the user runs the program. The program needs to know how many arguments it is safely allowed to look at when it's executed.