I'm making a program that takes a three-digit integer and splits it into two integers. 224 would become 220 and 4. 114 would become 110 and 4.
Basically, you do it with modulos. I wrote what I think should work and the compiler keeps saying that there is a missing parenthesis before the &big but any changes just make more errors happen.
#include <stdio.h>
void split_num(int complete, int *big, int *little){
*little = complete%10;
*big = complete - *little;
return;
}
int main()
{
int complete, big, little;
printf("Give an integer to split: \n");
scanf("%d", &complete);
void split_num(complete, &big, &little);
printf("Num split into 2 is : %d and %d", big, little);
return 0;
}
Take out the "void" in your call to split_num(). It's only used in the function declaration (to signify that it does not return a value), not in actual invocations of it.
The line (in main())
void split_num(complete, &big, &little);
should read
split_num(complete, &big, &little);
remove the void in the line "void split_num". You don't specify return values (void) when just calling a method.
You have an error in the following line:
void split_num( complete, &big, &little );
Remove the void return type and invoke the function like so:
split_num( complete, &big, &little );
The return; statement in the split_num( ... ) function is also unnecessary.
Related
I'm taking the CS50 class week 1 and I made the code work but I don't understand the custom functions part
void cat (int n)
I know that cat is your desired name for your function.
In my own understanding the code inside the parenthesis is the input that your custom function is taking (please correct me if my understanding is wrong)
but what I do not understand totally is the first word of the custom functions code like why is it void not int.
I would love it it you explained it in a much simpler English since English or programming vocabulary is pretty small atm.
Function format:
xxxxx yyyyy(zzzzz)
{
/* code */
return something;
}
xxxxx is the function return type. void means that function does not return anything to the caller.
yyyyy is the function name.
zzzzz are the function parameters. void means that function does not take any parameters. Parameters are separated by a comma. Parameter definition consists of type and parameter name.
examples:
int add(int x, int y)
{
return x + y;
}
the function add taking two integers as parameters and returning int
I do not understand totally is the first word of the custom functions
code like why is it void not int.
Programmer decided that function cat will not return anything
void cat (int n); // note the semicolon
This is a forward declaration of a function named cat that takes one int named n as an input parameter. It's declared void which means that the function does not return anything.
The definition of cat could look like this:
#include <stdio.h> // needed for printf etc.
void cat (int n) {
printf("the cat is %d years old\n", n); // note: using `n` here
// return; // not needed since the function is `void`
}
Forward declaration are made if you need to resolve circular dependencies:
void foo(int x) { if (x==1) bar(x+1); } // calls `bar`
void bar(int x) { if (x==1) foo(x+1); } // calls `foo`
This should not compile because when the compiler processes foo(), bar() is unknown. A forward declaration of bar() before foo() solves it:
void bar(int x); // forward declaration saves the situation
void foo(int x) { if (x==1) bar(x+1); }
void bar(int x) { if (x==1) foo(x+1); }
Forward declarations can also be used to declare all functions defined in the file at the top of the file and implement (define) them later. The list of functions then works as a sort of index of all the functions in the file. It's a matter of coding style. Example:
#include <stdio.h>
// forward declarations of all functions (except main):
void cat (int n);
// program entry point:
int main (void) {
cat(12); // calling cat with the argument 12 (an `int`)
return 0; // not strictly required when returning from main
}
// all the definitions follows:
void cat (int n) {
printf("the cat is %d years old\n", n); // prints: the cat is 12 years old
}
In your example, "void" is the return value of the function. In this case, the function is not defined to return a value and would therefor not have a "return" statement with a value.
Edit: But as pointed out below in a comment, it can have a "return" statement without a value.
The term has fallen out of use, but it may be more clear to (silently) regard the example given as a 'subroutine'. Whatever is done by cat() is to be done, but the perhaps many lines of fiddley code would distract from the flow of processing where cat() has been called. Putting those lines of code into a 'subroutine' means that the main body of code can be shorter and easier to understand.
Another benefit of a 'subroutine' is that the same processing can be done (called) from multiple locations without duplicating lines of code.
Here's a snippet of a contrived and trivial example I hope makes this plain. The task is to count from 0 to 'n', printing every so often, and then printing the final value reached:
#include <stdio.h>
// 'Subroutine' that provides some service
void out( int n ) {
/* this represents what could be many lines of code */
printf( "Have reached %d\n", n );
}
int main() {
int maxVal = 23; // some ceiling value
/* somewhere in the body of code */
int i = 0; // initial condition
out( i ); // output initial value
do {
i = i + 1; // processing
// output if a threshold reached
if( (i / 5) * 5 == i )
out( i );
} while( i < maxVal );
out( i ); // output final value
return 0;
}
Output:
Have reached 0
Have reached 5
Have reached 10
Have reached 15
Have reached 20
Have reached 23
I am creating a project and I encountered behavior that is not supposed to happen (at least as far as I know). I am trying to change values in a struct array inside of a function addOrder. in main() I give struct's address to a function addOrder (and this is the first warning). Then I try to change its contents in the named function. I should only be able to change using ->, however, I get errors this way and I can only change using data[0].someName
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define MENU_TITLE "----Welcome to order manager!---" // menu title
#define MENU_SIZE 4 //change based on menu options
#define INPUT_MSG "Please choose one of the following options" //enter input message (range is added later automatically)
#define SIZE 25 //size of option message array
#define STREET_NAME_SIZE 50 //size of street name array
#define BUILDING_NUMBER_SIZE 10 //size of building number array
#define EMAIL_SIZE 40 //size of email array
#define INPUT_PHONE_MAX 12
typedef struct Data{
char streetName[STREET_NAME_SIZE];
char buildingNumber[BUILDING_NUMBER_SIZE];
unsigned long long phoneNumber;
char email[EMAIL_SIZE];
}Data;
void loadOrderAmount(int *orderAmount);
void showMenu(char *menuTitle, int menuSize, char *inputMsg);
int getChoise();
void addOrder(Data *data, int *orderAmount);
void getEmail(char *email);
unsigned long long getPhoneNumber();
int main(){
int orderAmount = 0;
loadOrderAmount(&orderAmount);
Data data[orderAmount + 1];
int choise = 0;
showMenu(MENU_TITLE, MENU_SIZE, INPUT_MSG);
while(!choise){
choise = getChoise();
}
printf("\n");
switch(choise){
case 1:
addOrder(&data,&orderAmount); // This gives first warning
break;
case 2:
//removeOrder(data);
break;
case 3:
//editOrder(data);
break;
case 4:
printf("Have a nice day\n");
return 0;
}
printf("in main data %d\n",&data);
//printf("%s %s ",data[0].streetName,data[0].buildingNumber);
//printf("+%llu ",data[0].phoneNumber);
printf("in main %s %llu\n",data[0].email,data[0].phoneNumber);
return 0;
}
void addOrder(Data *data,int *orderAmount){
int amount = *orderAmount; //it is equal to 0
char email[41];
char street[51];
char buildingNumber[11];
printf("Adding an order...\n\n");
//++orderAmount;
// getStreetName(data, &orderAmount);
// getBuildingNumber(data,&orderAmount);
data[amount]->phoneNumber = getPhoneNumber(); //why this does not work?
getEmail(email);
strcpy(data[0].email,email); // why this works? its a function....
printf("In function data %d\n", data);
printf("in struct %s %llu\n",data[0].email, data[0].phoneNumber);
}
}
This is only a part of a code that is relevant and most functions are missing. Can anyone help me with this?
The function addOrder is declared like
void addOrder(Data *data, int *orderAmount);
But you are calling it passing the first argument of the type Data ( * )[orderAmount + 1]
addOrder(&data,&orderAmount);
You need to call it like
addOrder( data, &orderAmount );
Instead of this statement
data[amount]->phoneNumber = getPhoneNumber();
you have to write
data[amount].phoneNumber = getPhoneNumber();
And instead of this call
printf("In function data %d\n", data);
you have to write
printf("In function data %p\n", ( void * )data);
Pay attention to that within the function the expressions
data[amount]
and
data[0]
are not the same because amount is not equal to zero. The function is called with the argument orderAmount (passed by reference) that is assigned to amount.
This is how you solve this error:
Compiler points at the line addOrder(&data,&orderAmount); saying something strange "error passing argument 1 blablabla". We don't actually need to understand more than "error argument 1".
Could it be that the compiler is right and something is wrong with argument 1?
Hmm which one is argument 1, it must be &data.
Check the declaration of data, it is Data data[orderAmount + 1];. It's an array!
What did they teach us in beginner class? Ah, arrays decay to a pointer to the first element when passed to a function. So there is no need for &.
Change the call to addOrder(data,&orderAmount);
Compile again.
I am writing a c program with void main function in code blocks.
I just write return with no value.
The program is as below:
#include<stdio.h>
void main (void)
{
printf ("ali tariq\n");
return;
}
However, in the console window the program returns the value 16 in the console window. "Process returned 16"
I want to know why it is returning this value?
How can i utilize this value in windows using codeblocks?
Thanks
In (hosted) C the main function must return an int (C11§5.1.2.2.1[1]). By declaring it with a return type of void, and not specifying any return value you invoke undefined behaviour. This means the compiler is free to return anything and in your case it turns out to be 16.
You are not free to declare the return type of main as you wish. Why?
BECAUSE YOU DIDN'T WRITE THE CODE CALLING main(). Sorry 'bout the shouting, but someone else wrote that code and placed it in crt0.o or so. Your main() is linked against that code and it can't just return what it wants because that code expects an int. Always. It's already written and compiled. You understand this subtle point?
Because the C Standard says so. See other answer by Kninnug for Chapter and Verse.
In other words, your code invokes undefined behavior and it should be no surprise to find a garbage value where no value was provided.
So you expected a warning from the compiler? The better ones indeed will catch this with the right options. E.g. gcc and clang support -Wmain-return-type.
You should not use void main(), use int main() instead.
The program has undefined behavior. First of all according to the C Standard main without parameters shall be declared like
int main( void )
You declared the function as having return type void. In this case the process that starts the program can not get a valid return code of the program.
Just because a function is declared as void doesn't mean it won't return anything. On the x86, for example, a lot of calling conventions specify that the value in the register EAX after a function call is the return value of the function. So, if you have a C function that is declared void but the machine code for the function changes the value of EAX, that will get treated as the return value for the function.
EVERY "normal" program that terminate execution WITHOUT errors, must return ZERO.
So, your program must be:
#include<stdio.h>
int main (int argc, char *argv[]) // your program may have command line parameters
{
printf ("ali tariq\n");
return 0; // Program terminate with NO ERRORS
}
However there are cases when one program may terminate WITH errors.
Let's suppose this:
#include<stdio.h>
void main (int argc, char *argv[])
{
// program to make a division between two numbers
double a, b, res;
a = b = res = 0.0;
printf ("Enter 1st number: ");
scanf ("%lf", &a);
printf ("Enter 2nd number: ");
scanf ("%lf", &b);
if (b == 0) return 1; // division by '0' then return ERROR (any number != 0)
printf ("%f / %f = %f", a, b, a/b);
return 0; // NO ERROR
}
Now you may ask: «But where is the return value evaluated?
Answer: «By the Operating System.»
One batch file may run your program and read the integer YOU returned in the environment variable 'ERRORLEVEL'
I am very new to C programming and having trouble compiling what should be a very simple function. The function, called printSummary, simply takes 3 integers as arguments, then prints some text along with those integers. For example, if hits=1, misses=2, and evictions=3, then printSummary(hits,misses,evictions) should print the following:
hits:1 misses:2 evictions:3
Here is the code I'm using. Thanks in advance for any advice.
#include<stdio.h>
void printSummary(int hits, int misses, int evictions)
{
printf('hits: %d\n');
printf('misses: %d\n');
printf('evictions: %d\n');
}
int main()
{
int hit_count = 1;
int miss_count = 2;
int eviction_count = 3;
printSummary(hit_count, miss_count, eviction_count);
return 0;
}
Compiling this code gives me several warnings, but no errors. When I run the code, I get a segmentation fault. Like I said, I am fairly new to C so there is most likely a simply solution that I am just missing. Thanks in advance for any advice.
Make the below changes .
printf("hits: %d\n",hits);
printf("misses: %d\n",misses);
printf("evictions: %d\n",evictions);
printf has a
int printf(const char *format, ...)
prototype. So in the first argument you can pass format specifiers and in the next provide the actual variables/values to be printed out
errors are:
void printSummary(int hits, int misses, int evictions)
{
/* Name: printf
Prototype: int printf (const char *template, ...)
Description:
The printf function prints the optional arguments under the
control of the template string template to the stream stdout.
It returns the number of characters printed,or a negative value if
there was an output error.*/
printf("hits: %d\n", hits); // don't use ' it is used only for char variable for example: char a = 'c';
printf("misses: %d\n", misses);
printf("evictions: %d\n", evictions);
}
Your printf function is not being called correctly. You have to include the integers needed to print:
printf("hits: %d\n", hits);
printf("misses: %d\n", misses);
printf("evictions: %d\n", evictions);
Read more about the printf function here.
I am learning C and I am studying functions. So, I read that when I implement my own function I have to declare it before the main(). If I miss the declaration the compiler will get an error message.
As I was studying this example (finds if the number is a prime number),
#include <stdio.h>
void prime(); // Function prototype(declaration)
int main()
{
int num, i, flag;
num = input(); // No argument is passed to input()
for(i=2,flag=i; i<=num/2; ++i,flag=i)
{
flag = i;
if(num%i==0)
{
printf("%d is not prime\n", num);
++flag;
break;
}
}
if(flag==i)
printf("%d is prime\n", num);
return 0;
}
int input() /* Integer value is returned from input() to calling function */
{
int n;
printf("\nEnter positive enter to check: ");
scanf("%d", &n);
return n;
}
I noticed that a function prime() is declared, but in the main, a function, input(), is called and also the function input() is implemented at the bottom. Ok, I thought it was a mistake and I change the name from prime to input.
However if I delete the declaration and I don’t put any there, the program is compiled without errors and it runs smoothly. (I compile and run it on Ubuntu.)
Is it necessary to declare a void function with not arguments?
If you don't have a forward declaration of your function before the place of usage, the compiler will create implicit declaration for you - with the signature int input(). It will take the name of the function you called, it will assume that the function is returning int, and it can accept any arguments (as Bartek noted in the comment).
For this function, the implicit declaration matches the real declaration, so you don't have problems. However, you should always be careful about this, and you should always prefer forward declarations instead of implicit ones (no matter if they are same or not). So, instead of just having forward declaration of the void prime() function (assuming that you will use it somewhere), you should also have a forward declaration of int input().
To see how can you pass any number of the arguments, consider this:
#include <stdio.h>
// Takes any number of the arguments
int foo();
// Doesn't takes any arguments
int bar(void)
{
printf("Hello from bar()!\n");
return 0;
}
int main()
{
// Both works
// However, this will print junk as you're not pushing
// Any arguments on the stack - but the compiler will assume you are
foo();
// This will print 1, 2, 3
foo(1, 2, 3);
// Works
bar();
// Doesn't work
// bar(1, 2, 3);
return 0;
}
// Definition
int foo(int i, int j, int k)
{
printf("%d %d %d\n", i, j, k);
return 0;
}
So, inside the definition of the function you're describing function arguments. However, declaration of the function is telling the compiler not to do any checks on the parameters.
Not declaring a prototype and relying on default argument/return type promotion is dangerous and was a part of old C. In C99 and onward it is illegal to call a function without first providing a declaration or definition of the function.
my question is, is it necessary to declare a void function with not arguments?
Yes. For this you have to put void in the function parenthesis.
void foo(void);
Declaring a function like
void foo();
means that it can take any number of arguments.
If prime is not used, then omit the declaration.
The code won't compile as C++, because the compiler would complain that function input is used but not declared. A C compiler might issue a warning, but C is more relaxed and does an implicit declaration of input as int input() which means that you can pass any value to input and input returns an int.
It is good style to always provide a function declaration before using the function. Only if you do this the compiler can see if you are passing too few, too many or wrongly typed arguments and how to correctly handle the return value (which might be short or char instead of int).