#same thing?
19 messages · Page 1 of 1 (latest)
it works the same
but i dont recommend creating a int& variable
because why
why you need to create it
you can just print n twice
and it will work
from reference you can change the n(if im not mistaken)
so
you just creating a reference object which does nothing
second variant is better i think
and
dont use global variables
give me a minute
i will try to explain
int main()
{
int n = 234; /* this is local variable because it is in function */
} // n will be destroyed here
-----------------------------------------------------------------
if(int n = some_function(); n == 2) /* n is local variable because it was created in if statement*/
{
n += 2;
}// n will be destroy here
-----------------------------------------------------------------
int n = 234; /* n is a global variable because it wasn't created in function, or if statements, switch statements etc. */
int main()
{
if(int n = some_function(); n == 52)
{
n += 7;
}
}
i'll recomend you to change printN function like that
#include <iostream>
void print_number_twice(int n)
{
std::cout << n << '\n' << n << '\n';
}
int main(void)
{
int n{2};
print_number_twice(n);
}
and make this
#include <iostream>
void print_number_twice(int);
int main(void)
{
int n{2};
print_number_twice(n);
}
void print_number_twice(int n)
{
std::cout << n << '\n' << n << '\n';
}
or put the function to the .h file like this
// functions.h
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
void print_number_twice(int);
#endif
// functions.cpp
#include <iostream>
#include "functions.h"
void print_number_twice(int n)
{
std::cout << n << '\n' << n << '\n';
}
// main.cpp
#include "functions.h"
int main(void)
{
int n{2};
print_number_twice(n);
}