This is a problem from my course lesson where we are learning C-language. Why do I get the error below? I tried to search it on Google and I couldn't find anything. The error is not especially helpful with the info provided as I can't change the line it references.
main.c:21:14: error: void value not ignored as it ought to be
21 | isChanged = AdjustState(waterTemperature, &waterState);
| ^
For the lesson I am not allowed to change the main function.
#include <stdio.h>
#include <stdbool.h>
void AdjustState(int waterTemperature, char* waterState) {
if (waterTemperature < 100) {
*waterState = 'L';
}
if (waterTemperature < 100) {
*waterState = 'G';
}
}
int main(void) {
int waterTemperature;
char waterState;
bool isChanged;
waterState = 'B';
scanf("%d", &waterTemperature);
isChanged = AdjustState(waterTemperature, &waterState);
if (isChanged) {
printf("Water state is changed to %c.\n", waterState);
}
else {
printf("Water state %c is not changed.\n", waterState);
}
return 0;
}
CodePudding user response:
You should change the return type of the function AdjustState
and have it return something that fit to the function main
.
It looks like it should return if the function changed the value pointed at by waterState
, it can be like this:
int AdjustState(int waterTemperature, char* waterState) {
char originalWaterState = *waterState;
if (waterTemperature < 100) {
*waterState = 'L';
}
if (waterTemperature < 100) {
*waterState = 'G';
}
return *waterState != originalWaterState;
}
CodePudding user response:
The function has the return type void
void AdjustState(int waterTemperature, char* waterState) {
if (waterTemperature < 100) {
*waterState = 'L';
}
if (waterTemperature < 100) {
*waterState = 'G';
}
}
Thus this statement
isChanged = AdjustState(waterTemperature, &waterState);
is invalid. A function with the return type void
returns nothing.
If you may not change the function declaration then you should write for example
waterState = 'B';
char currentWaterState = waterState;
scanf("%d", &waterTemperature);
AdjustState(waterTemperature, &waterState);
isChanged = currentWaterState != waterState;
// ...
Also it seems that there is a typo within the function
if (waterTemperature < 100) {
*waterState = 'L';
}
if (waterTemperature < 100) {
*waterState = 'G';
}
The both if statements have the same condition expression. Check the conditions and change one or them.
Maybe you need to write something like the following
void AdjustState(int waterTemperature, char* waterState) {
if (waterTemperature < 100) {
*waterState = 'L';
}
else {
*waterState = 'G';
}
}
Or alternatively
void AdjustState(int waterTemperature, char* waterState) {
*waterState = waterTemperature < 100 ? 'L' : 'G';
}