The correct condition is as follows:
if (mes >= 1 && mes <= 12 && dia >= 1 && dia <= 31 && ano >= 1) {
printf("\nEssa data eh valida!");
} else {
printf("\nEssa data nao eh valida!");
}
Don’t confuse the operator &&
with ==
, because they are very different in both behavior and conceptually.
On terms dia>0
, mes>0
and ano>0
are redundant in the face of the other restrictions that already exist, and therefore are unnecessary.
Ah, and this of course, still disregards the fact that not every month has a day 31 and that February may have 28 or 29 days. For this, some more complex conditions would be necessary, but as you are just beginning, let’s stick with this simpler case that every month can have 31 days. But if you really want to know, to deal with these cases (considering that the calendar is always Gregorian), the condition would be as follows:
if (dia >= 1 && dia <= 31 && mes >= 1 && mes <= 12 && ano >= 1 && (dia <= 28 || mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12 || (dia <= 30 && mes != 2) || (dia == 29 && ano % 4 == 0 && (ano % 100 != 0 || ano % 400 == 0)))) {
The use of if
s chained does not occur the way you imagined. If you do not know yet how the if
without the {
and the }
that follow him, so always use the {
and the }
on it. Only use the if
without the {
and the }
when you’re sure of how it works and already know when it’s a good idea or not (and most of the time, don’t put the {
and the }
in the if
it’s not a good idea).